用JS调用C#方法

我正在尝试创建一个根据用户属性动态更改的登录页面,特别是登录到cookie的用户名和角色。 登录工作正常; 但是,因为我使用一种非常简单的方式来调用C#函数,所以当调用包含内联C#调用的javascript方法时,它会跳过该方法中的所有其他代码行并适合C#函数。

我已经读过,更好的方法是使用Webmethods和JQuery Ajax,但是,我无法在我的C#文件中声明webmethods。

我的前端看起来如下

为Login.aspx

    PAM testing       
function logCookie(){ document.cookie = "user=" + document.getElementById("Login1_UserName").value;// this is the id of username input field once displayed in the browser } function testFunction() { ; } function process(){ logCookie(); testFunction(); }

我的C#代码看起来像这样

Login.aspx.cs

 using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.EnterpriseServices; public partial class Login : System.Web.UI.Page { int status; int role; SqlConnection conn; SqlCommand command; SqlDataReader reader; protected string Login1_Authenticate() { // create an open connection conn = new SqlConnection("Data Source=xxx;" + "Initial Catalog=xxx;" + "User ID=xxx;Password=xxx"); conn.Open(); //string userName; //userName = Convert.ToString(Console.ReadLine()); // create a SqlCommand object for this connection command = conn.CreateCommand(); command.CommandText = "EXEC dbo.SP_CA_CHECK_USER @USER_ID = '"+Login1.UserName+"', @PASSWORD = '"+Login1.Password+"'"; command.CommandType = CommandType.Text; // execute the command that returns a SqlDataReader reader = command.ExecuteReader(); // display the results while (reader.Read()) { status = reader.GetInt32(0); } // close first reader reader.Close(); //---------- existTest(); return "the login process is finished"; } public static string GetData(int userid) { /*You can do database operations here if required*/ return "my userid is" + userid.ToString(); } public string existTest() { if (status == 0) { //login Session["userID"] = Login1.UserName; command.CommandText = "EXEC dbo.SP_CA_RETURN_USER_ROLE @USER_ID = '" + Login1.UserName + "'"; reader = command.ExecuteReader(); while (reader.Read()) { role = reader.GetInt32(0); } Session["roleID"] = role; if (Session["userID"] != null) { string userID = (string)(Session["userID"]); //string roleID = (string)(Session["roleID"]); } Response.Redirect("Home.aspx"); } else { //wrong username/password } // close the connection reader.Close(); conn.Close(); return "process complete"; } } 

创建你的方法作为web服务(web-api很好),然后使用jS ajax调用它,这是我用web-api和JS的一个例子(这是发布数据,如果你没有任何内容发布,请使用get)

 $.ajax({ type: 'Post', contentType: "application/json; charset=utf-8", url: "//localhost:38093/api/Acc/", //method Name data: JSON.stringify({ someVar: 'someValue', someOtherVar: 'someOtherValue'}), dataType: 'json', success: someFunction(), // callback above error: function (msg) { alert(msg.responsetext); } });