从客户端调用服务器端函数

Call server side function from Client Side

本文关键字:函数 服务器端 调用 客户端      更新时间:2023-09-26

我使用的是Master和Content页面。我的客户端功能是-

 <script type="text/javascript">
    function StateChange(txtState) {
        var state = document.getElementById(txtState);
        PageMethods.StateSelectionChange(state.value, OnSuccess, onFailed);
    }
    function OnSuccess(state, userContext, methodName) {
        alert(state);
    }
    function onFailed(state, userContext, methodName) {
        alert(state);
    }
</script>

和服务器端代码是-

 public static string StateSelectionChange(string state)
{
    //txtCity.Text = "";
    //if (txtState.Text != "")
    //{
    //    SqlDataReader dr = cm.Allstate(txtState.Text);
    //    if (dr.Read())
    //    {
    //        con.Close();
    //        AutoCompleteExtender2.ContextKey = txtState.Text;
    //        txtCity.Enabled = true;
    //        txtCity.Focus();
    //    }
    //    else
    //    {
    //        con.Close();
    //        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "alert('State is not exist');", true);
    //        txtState.Text = "";
    //        txtState.Focus();
    //    }
    //}
    return (state);
}

我无法访问该代码的注释部分(文本框和类主函数),因为将函数声明为静态。如果我从这个函数中删除静态单词,那么它就不应该从客户端调用。

最后我想从客户端使用Java脚本/ajax请求调用非静态函数

你不能这样做,因为所有控件都是实例,你只能从静态方法访问静态成员。我使用的一个工作是将控件值作为参数传递给服务器端方法。