How to make HtmlSelect Control with OnChange event to trigger C# code behind function

梦想的初衷 提交于 2020-12-25 18:40:48

问题


How should I make "Html Select Control" with OnChange event to trigger C# code behind function
like ASP.NET SelectedIndexChanged of the DropDownList Control

For example
Front end

<select runat="server" id="xx" onserverchange="xx_ServerChange">
 <option>A</option>
 <option>B</option>
 <option>C</option>
</select>

Back End

protected void xx_ServerChange(object sender, EventArgs e)
{

}

PS:
1.Not like this Select server changed event ,because it has to make another event button.
2.Don't use asp:DropDownList
3.Please don't use any redirect methods like Ajax or JQuery etc...


回答1:


I've found a great way to handle my problems, showing my ideas as following code

Front End

  <select id="StartDate"  onserverchange="StartDate_ServerChange" runat="server">
  </select>

Back End

protected void Page_Load(object sender, EventArgs e)
{     
   ClientScriptManager cs = Page.ClientScript;
   this.StartDate.Attributes.Add("onchange", cs.GetPostBackEventReference(this.StartDate, this.StartDate.ID));
}
protected void StartDate_ServerChange(object sender, EventArgs e)
{

}

PS: two references
https://msdn.microsoft.com/en-us/library/ms153112(v=vs.110).aspx
https://blog.csdn.net/lovegonghui/article/details/51942241




回答2:


If I'm getting it right, you need to use another control to trigger the code behind. Just add the button and access the state of the select

    <select runat="server" id="xx">
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Code behind:

    protected void Button1_Click(object sender, EventArgs e)
    {
        int index = xx.SelectedIndex;
    }



回答3:


I think you need to submit the form for the change to be registered:

<form id="myForm">
    <select runat="server" id="xx" onchange="myForm.submit()" onserverchange="xx_ServerChange">
     <option>A</option>
     <option>B</option>
     <option>C</option>
    </select>
</form>



回答4:


Use Ajax call in xx_ServerChange function from JavaScript

$.ajax({
    type: 'POST',
    url: 'PageName.aspx/functionName()',
    data: '{ }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(msg) {
        // Do something interesting here.
    }
});


来源:https://stackoverflow.com/questions/51395458/how-to-make-htmlselect-control-with-onchange-event-to-trigger-c-sharp-code-behin

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