如何使用javascript调用ASP.NET c#方法

mik*_*eri 32 javascript c# asp.net

有谁知道如何使用javascript调用服务器端c#方法?我需要做的是在选择取消时停止导入,或者如果选择确定则继续导入.我正在使用visual studio 2010和c#作为我的编程语言

这是我的代码:

private void AlertWithConfirmation()            
{                 
    Response.Write(
        "<script type=\"text/javascript\">" +     
            "if (window.confirm('Import is currently in progress. Do you want to continue with importation? If yes choose OK, If no choose CANCEL')) {" +     
                "window.alert('Imports have been cancelled!');" +     
            "} else {" +   
                "window.alert('Imports are still in progress');" +     
            "}" +      
        "</script>");   
}
Run Code Online (Sandbox Code Playgroud)

Fah*_*ain 69

PageMethod为Asp.Net AJAX提供了一种更简单,更快捷的方法我们可以通过释放AJAX的强大功能轻松改善Web应用程序的用户体验和性能.我喜欢AJAX中最好的东西之一就是PageMethod.

PageMethod是一种可以在java脚本中公开服务器端页面方法的方法.这带来了很多机会,我们可以在不使用缓慢而烦人的回发的情况下执行大量操作.

在这篇文章中,我将展示ScriptManager和PageMethod的基本用法.在这个例子中,我正在创建一个用户注册表单,用户可以在其中注册他的电子邮件地址和密码.这是我要开发的页面的标记:

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

要设置页面方法,首先必须在页面上拖动脚本管理器.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Run Code Online (Sandbox Code Playgroud)

还要注意我已经改变了EnablePageMethods="true".
这将告诉ScriptManager我将从客户端调用PageMethods.

现在,下一步是创建服务器端功能.
这是我创建的函数,该函数验证用户的输入:

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password cannot be less than 5 chars";
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

要告诉脚本管理器这个方法可以通过javascript访问,我们需要确保两件事:
第一:这个方法应该是'public static'.
第二:上面的代码中应该有一个[WebMethod]标签.

现在我创建了创建帐户的服务器端功能.现在我们必须从客户端调用它.以下是我们如何从客户端调用该函数:

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

要调用我的服务器端方法注册用户,ScriptManager会生成一个可在PageMethods中使用的代理功能.
我的服务器端功能有两个参数,即电子邮件和密码,在这些参数之后我们必须再给两个函数名称,如果方法成功执行(第一个参数即onSucess)或方法失败(第二个参数即结果)将运行.

现在每件事情都准备好了,现在我已经添加OnClientClick="Signup();return false;"了我的注册按钮.所以这里完整的aspx页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

  • [WebMethod]是[System.Web.Services.WebMethod]的缩写。 (3认同)
  • 谢谢,不知道这个。就我而言,由于“静态”WebMethod,我无法访问我的类函数。使用 UpdatePanel (UpdateMode="Conditional") 解决了这个问题,一个 css 隐藏的 asp:Button 的 onClick 函数可以访问我的类函数。通过 JavaScript 点击按钮。对我有用。希望这是其他人的替代方案:-)。 (2认同)

Wra*_*ath 6

我怀疑您需要进行Ajax呼叫。这是jQuery制作的Ajax示例,可以帮助您入门。该代码将用户登录到我的系统,但返回布尔值是否成功。注意方法背后的代码上的ScriptMethod和WebMethod属性。

在标记中:

 var $Username = $("#txtUsername").val();
            var $Password = $("#txtPassword").val();

            //Call the approve method on the code behind
            $.ajax({
                type: "POST",
                url: "Pages/Mobile/Login.aspx/LoginUser",
                data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) },
                success: function (msg) {
                    if (msg.d == true) {
                        window.location.href = "Pages/Mobile/Basic/Index.aspx";
                    }
                    else {
                        //show error
                        alert('login failed');
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)

在后面的代码中:

/// <summary>
/// Logs in the user
/// </summary>
/// <param name="Username">The username</param>
/// <param name="Password">The password</param>
/// <returns>true if login successful</returns>
[WebMethod, ScriptMethod]
public static bool LoginUser( string Username, string Password )
{
    try
    {
        StaticStore.CurrentUser = new User( Username, Password );

        //check the login details were correct
        if ( StaticStore.CurrentUser.IsAuthentiacted )
        {
            //change the status to logged in
            StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn;

            //Store the user ID in the list of active users
            ( HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int> )[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID;

            return true;
        }
        else
        {
            return false;
        }
    }
    catch ( Exception ex )
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)