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

时间:2022-02-15 03:17:05

Does anyone know how to call a server-side c# method using javascript? What i need to do is to stop imports if Cancel is chosen or to continue importing if ok is chosen. I am using visual studio 2010 and c# as my programming lanaguage

有人知道如何使用javascript调用服务器端c#方法吗?我需要做的是选择Cancel时停止导入,选择ok时继续导入。我正在使用visual studio 2010和c#作为我的编程语言

This is my code:

这是我的代码:

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>");   
}

5 个解决方案

#1


60  

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod对于Asp来说是一种更容易、更快的方法。Net AJAX可以通过释放AJAX的力量来轻松地提高web应用程序的用户体验和性能。我在AJAX中最喜欢的一件事就是PageMethod。

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

PageMethod是一种在java脚本中公开服务器端页面方法的方法。这给我们带来了很多机会,我们可以执行很多操作,而不用使用缓慢和烦人的post back。

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

在这篇文章中,我展示了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>

To setup page method, first you have to drag a script manager on your page.

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

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

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

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

现在,下一步是创建一个服务器端函数。这里是我创建的函数,这个函数验证用户的输入:

[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;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

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

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

现在我已经创建了创建帐户的服务器端函数。现在我们必须从客户端调用它。下面是我们如何从客户端调用这个函数:

<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>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

要调用我的服务器端方法Register user, ScriptManager会生成一个在PageMethods中可用的代理函数。我的服务器端函数有两个参数,即电子邮件和密码,在这两个参数之后,如果方法成功执行(第一个参数即onSucess)或方法失败(第二个参数即result),我们必须再给出两个函数名。

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

现在一切似乎都准备好了,现在我在我的注册按钮上添加了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>

#2


4  

You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.

我怀疑您需要执行Ajax调用。下面是一个由jQuery生成的Ajax示例。代码将用户登录到我的系统,但返回一个bool,以判断它是否成功。注意方法后面的代码中的ScriptMethod和WebMethod属性。

in markup:

在标记:

 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');
                    }
                }
            });

In Code Behind:

在代码后面:

/// <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;
    }
}

#3


3  

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

我将继续提供一个使用jQuery的解决方案,这意味着如果您还没有…

Import the jQuery library in your page mark-up:

在页面标记中导入jQuery库:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

然后创建另一个*。js脚本文件(我将其称为ExecutePageMethod,因为这是它要公开的惟一方法)并导入:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

在新添加的文件中,添加下面的代码(我记得从其他地方提取了这个代码,所以其他人应该得到赞扬):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

然后,您需要使用适当的属性来增强.NET页面方法,例如:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

现在,在您的页面标记中,在脚本块中或从另一个脚本文件中,您可以调用这个方法,如下所示:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

显然,您需要实现OnSuccess和OnFailure方法。

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

要使用结果,例如在OnSuccess方法中,您可以使用parseJSON方法,如果结果变得更复杂(例如,在本例中或返回一个类型数组),该方法将它解析为对象:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

这个ExecutePageMethod代码特别有用,因为它可以重用,所以不必管理$。ajax调用可能要执行的每个页面方法,只需将页面、方法名和参数传递给此方法。

#4


1  

The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.

对于c#开发人员来说,Jayrock RPC库是一个很好的工具,可以用一种很熟悉的方式来实现这一点。它允许您使用所需的方法创建. net类,并将该类作为脚本(以迂回的方式)添加到页面中。然后可以创建类型的js对象,并调用方法,就像其他对象一样。

It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!

它本质上隐藏了ajax实现并以familliar格式呈现RPC。记住,最好的选择是使用ASP。NET MVC和使用jQuery ajax调用的动作方法-更简洁,更少混乱!

#5


0  

There are several options. You can use the WebMethod attribute, for your purpose.

有几个选项。您可以为您的目的使用WebMethod属性。

#1


60  

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod对于Asp来说是一种更容易、更快的方法。Net AJAX可以通过释放AJAX的力量来轻松地提高web应用程序的用户体验和性能。我在AJAX中最喜欢的一件事就是PageMethod。

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

PageMethod是一种在java脚本中公开服务器端页面方法的方法。这给我们带来了很多机会,我们可以执行很多操作,而不用使用缓慢和烦人的post back。

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

在这篇文章中,我展示了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>

To setup page method, first you have to drag a script manager on your page.

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

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

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

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

现在,下一步是创建一个服务器端函数。这里是我创建的函数,这个函数验证用户的输入:

[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;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

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

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

现在我已经创建了创建帐户的服务器端函数。现在我们必须从客户端调用它。下面是我们如何从客户端调用这个函数:

<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>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

要调用我的服务器端方法Register user, ScriptManager会生成一个在PageMethods中可用的代理函数。我的服务器端函数有两个参数,即电子邮件和密码,在这两个参数之后,如果方法成功执行(第一个参数即onSucess)或方法失败(第二个参数即result),我们必须再给出两个函数名。

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

现在一切似乎都准备好了,现在我在我的注册按钮上添加了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>

#2


4  

You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.

我怀疑您需要执行Ajax调用。下面是一个由jQuery生成的Ajax示例。代码将用户登录到我的系统,但返回一个bool,以判断它是否成功。注意方法后面的代码中的ScriptMethod和WebMethod属性。

in markup:

在标记:

 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');
                    }
                }
            });

In Code Behind:

在代码后面:

/// <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;
    }
}

#3


3  

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

我将继续提供一个使用jQuery的解决方案,这意味着如果您还没有…

Import the jQuery library in your page mark-up:

在页面标记中导入jQuery库:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

然后创建另一个*。js脚本文件(我将其称为ExecutePageMethod,因为这是它要公开的惟一方法)并导入:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

在新添加的文件中,添加下面的代码(我记得从其他地方提取了这个代码,所以其他人应该得到赞扬):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

然后,您需要使用适当的属性来增强.NET页面方法,例如:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

现在,在您的页面标记中,在脚本块中或从另一个脚本文件中,您可以调用这个方法,如下所示:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

显然,您需要实现OnSuccess和OnFailure方法。

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

要使用结果,例如在OnSuccess方法中,您可以使用parseJSON方法,如果结果变得更复杂(例如,在本例中或返回一个类型数组),该方法将它解析为对象:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

这个ExecutePageMethod代码特别有用,因为它可以重用,所以不必管理$。ajax调用可能要执行的每个页面方法,只需将页面、方法名和参数传递给此方法。

#4


1  

The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.

对于c#开发人员来说,Jayrock RPC库是一个很好的工具,可以用一种很熟悉的方式来实现这一点。它允许您使用所需的方法创建. net类,并将该类作为脚本(以迂回的方式)添加到页面中。然后可以创建类型的js对象,并调用方法,就像其他对象一样。

It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!

它本质上隐藏了ajax实现并以familliar格式呈现RPC。记住,最好的选择是使用ASP。NET MVC和使用jQuery ajax调用的动作方法-更简洁,更少混乱!

#5


0  

There are several options. You can use the WebMethod attribute, for your purpose.

有几个选项。您可以为您的目的使用WebMethod属性。