Invoke ASP.NET TextChanged event from JavaScript using __doPostBack

馋奶兔 提交于 2019-12-02 03:53:32

I've tried this, and it works for me:

<asp:TextBox runat="server" ID="txtSearch" OnTextChanged="txtSearch_TextChanged"></asp:TextBox>
<input type="button" value="submit" onclick="<%= GetOnChangedScript() %>" />

The server side asp:TextBox, and the client side input which fires __doPostBack on click. The __doPostBack script is generated through PostBackOptions:

protected string GetOnChangedScript()
{
    var options = new PostBackOptions(txtSearch, string.Empty);
    options.AutoPostBack = true;
    options.RequiresJavaScriptProtocol = true;
    var script = Page.ClientScript.GetPostBackEventReference(options);
    return script;
}

The txtSearch_TextChanged event handler fires when the value of text box is changed, and the submit button is clicked.

But note, for controls like TextBox the text is stored in the viewstate; the new text entered by the user stores in the form data. When the TextBox load the viewstate data, it gets the old value. This is compared with the new value that comes in the form. If the values are different, the TextChanged event is fired. If no, the event handler won't be fired. This is the reason for the Page_Load event get fired (postback occured), but txtSearch_TextChanged didn't fire due to the value of the TextBox didn't change.

function initTxtBox(){  $('#<%=txtBox.ClientID%>').on('keyup change', function() {setTimeout('txtpostback()', 0); return false;});}
function txtpostback(){__doPostBack('" + txtCadastreNumber.UniqueID + @"','');
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initTxtBox);

Set auotpostback property to false for your txtbox and AutoEventWireup="true" for your control or page declaration. OnTextChanged event server-side will work too. if you don't use jquery in your project, let me know and I give you some javascript example without jquery using.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!