简体   繁体   中英

How can I call a codebehind function from JavaScript?

I have a JavaScript function which i call in the onchange handler of a dropdownlist. If the selected value of dropdownlist is "1" i want to call one function in codebehind. Following is the function in JavaScript:

function  GetAdmissionType()
    {
        InitComponents();
        var type="";
        type=document.getElementById(dlAdmissionType.id).value;
        document.getElementById(hdnAdmissionType.id).value=document.getElementById(dlAdmissionType.id).value;
        if(type=="1")
        {
        }
  }

If type is 1 then i want to work following code in codebehind

public void LoadSemesters()
{
   //code to load other dropdownlists
}

Can anybody help to call function in codebehind from JavaScript?

最简单的方法是将代码隐藏功能公开为Web服务调用,并使用类似jQuery的东西从Javascript调用它。

It may depend on what you want to do with the other values in the drop-down list. But, the easiest way to do this is to wrap your drop-down list in an update panel and handle the OnSelectedIndexChanged event in your code-behind.

ASPX page:

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                <asp:ListItem Value="1">item 1</asp:ListItem>
                <asp:ListItem Value="2">item 2</asp:ListItem>
                <asp:ListItem Value="3">item 3</asp:ListItem>
                <asp:ListItem Value="4">item 4</asp:ListItem>
            </asp:DropDownList>
        </ContentTemplate>
    </asp:UpdatePanel>

Code behind:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch (DropDownList1.SelectedValue)
    {
        case "1":
            LoadSemesters();
            break;
        case "2":
        case "3":
        case "4":
        default:
            // do something
            break;
    }
}

Then you wouldn't need to do any javascript processing (unless you wanted to).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM