如何调用TextBox WebForm控件的TextChanged

How to call TextChanged of TextBox WebForm Control

我使用 TextBox 配置为 Bootstrap Datetimepicker 的 WebForm 控件。 我需要启动服务器端 TextChanged 事件。 我的代码不起作用,所以它不调用服务器端部分。

HTML

<div class='datepicker input-group date' id='datetimepickerStart'>
                                    <asp:TextBox ID="StartDate" class="form-control dateField" placeholder="Fecha" required runat="server" OnTextChanged="StartDate_TextChanged"></asp:TextBox>
     <span class="input-group-addon">
     <span class="glyphicon glyphicon-calendar"></span>
</span>
</div>

C#

protected void StartDate_TextChanged(object sender, EventArgs e)
{
    // It does not fire :(        
}

我试着像这样强迫这个事件,但没有快乐。

JS

$('#datetimepickerStart').datetimepicker();

$('#datetimepickerStart').datetimepicker().on('dp.change', function (event) {
       console.log(event.date);
      $('#StartDate').change(); // It does not help
      $('#StartDate').html(event.date); // It does not help             
});

知道如何解决吗?

方法名称不正确,将 autopostback= 'true' 添加到文本框

为了在您离开文本框时触发 TextChanged 事件,您必须将 TextBox 控件的 AutoPostBack 属性 设置为 true。

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.autopostback(v=vs.110).aspx

<asp:TextBox ID="StartDate" class="form-control dateField" autopostback="true" placeholder="Fecha" required runat="server" OnTextChanged="StartDate_TextChanged"></asp:TextBox>

您还需要确保 OnTextChanged 事件处理程序的名称与代码中方法的名称相匹配(也许这只是一个拼写错误)。

最后,我发现 TextChanged 事件有点挑剔,会导致不需要的回发、页面滚动、失去焦点等,因此您可能需要考虑使用客户端解决方案(例如。JQuery) 代替。

将此行更改为

<asp:TextBox ID="StartDate" class="form-control dateField" placeholder="Fecha" AutoPostBack="True" required runat="server" OnTextChanged="EndDate_TextChanged"></asp:TextBox>

会好的

解决方案是添加 ApiController 并通过 JQuery 使用我需要的内容。

https://blogs.msdn.microsoft.com/henrikn/2012/02/23/using-asp-net-web-api-with-asp-net-web-forms/

默认ASP.Net页面缓存所有服务器控件更改事件并在回发事件后执行。 因此,通过将控件的 Autopostback 属性 设置为 true 来覆盖此默认值,如下所示。

在 Internet 上进行了大量搜索后,我找到了对我有用的解决方案:

$('#datetimepickerStart').datetimepicker().on('dp.change', function (event) {
    __doPostBack('<%= Page.ClientID %>');
});

关于代码隐藏:

public void RaisePostBackEvent()
{
    // Do whatever, maybe call the OnTextChange method.
}

你甚至可以像这样传递一些参数:

__doPostBack('<%= Page.ClientID %>', argument);

public void RaisePostBackEvent(string Arg){...}