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

有谁知道如何调用服务器端的C#方法使用JavaScript? 我需要做的是停止导入,如果select取消或继续导入,如果select好。 我正在使用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>"); } 

PageMethod是Asp.Net AJAX的一种更简单快捷的方法通过释放AJAX的力量,我们可以轻松地提高Web应用程序的用户体验和性能。 我喜欢AJAX中最好的一件事就是PageMethod。

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

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

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

要设置页面方法,首先你必须在你的页面上拖动一个脚本pipe理器。

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

另外请注意,我已经改变了EnablePageMethods="true"
这将告诉ScriptManager,我将从客户端调用PageMethods。

现在下一步是创build一个服务器端function。
这是我创build的函数,这个函数validation用户的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; } 

为了告诉脚本pipe理器,这个方法可以通过javascript访问,我们需要确保两件事情:
首先:这个方法应该是“公共静态的”。
第二:在上面的代码中应该有一个上面的方法[WebMethod]标签。

现在我已经创build了创build帐户的服务器端function。 现在我们必须从客户端调用它。 以下是我们如何从客户端调用该函数:

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

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

现在,每件事似乎准备好了,现在我已经添加OnClientClick="Signup();return false;" 在我的注册button。 所以在这里完成我的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> 

你将需要做一个我怀疑的Ajax调用。 这是一个由jQuery调用的Ajax的例子,让你开始。 代码将用户login到我的系统,但返回一个布尔值,以确定它是否成功。 请注意方法后面的代码的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'); } } }); 

在代码后面:

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

我将继续前进,并提供一个解决scheme,使用jQuery,这意味着如果你还没有…,你将需要导入库…

在页面标记中导入jQuery库:

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

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

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

在新添加的文件中,添加下面的代码(我记得把它从其他地方拉出来,所以其他人真的值得称赞):

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

然后,您将需要使用适当的属性来扩充您的.NET页面方法,如下所示:

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

现在,在页面标记中,在script块或其他脚本文件中,可以调用方法,如下所示:

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

显然你需要实现OnSuccessOnFailure方法。

要使用结果,比如在OnSuccess方法中,可以使用parseJSON方法,如果结果变得更加复杂(例如,或者返回一个types数组),这个方法将会把它parsing成对象:

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

这个ExecutePageMethod代码是特别有用的,因为它是可重用的,所以你不需要为每个你想要执行的页面方法pipe理$.ajax调用,而只需要将页面,方法名称和parameter passing给这个方法。

Jayrock RPC库对于C#开发人员来说是一个非常好的家庭聚会的好工具。 它允许你用你需要的方法创build一个.NET类,并把这个类作为一个脚本(以一种迂回的方式)添加到你的页面中。 然后,您可以像创build其他对象一样创buildtypes的js对象并调用方法。

它基本上隐藏了Ajax实现,并以familliar格式呈现RPC。 请注意,最好的select实际上是使用ASP.NET MVC,并使用jQuery ajax调用动作方法 – 更简洁,更简单!

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