【问题标题】:Call C# Method with JS用 JS 调用 C# 方法
【发布时间】:2014-07-10 20:45:52
【问题描述】:

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

我已阅读到解决此问题的更好方法是使用 Webmethods 和 JQuery Ajax,但是,我无法在我的 C# 文件中声明 webmethods。

我的前端如下所示

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!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>PAM testing</title>
    <link rel="stylesheet" type="text/css" href="Styles/Site.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="Scripts/JScript.js"></script>
</head>
<body>
    <div id="banner">PAM Testing Tool</div>
    <div id="content">
        <form id="form1" runat="server" style="margin-left: 25%; text-align: center; height: 41px; width: 292px;">
            <%--Login ASP Object--%>
            <asp:Login ID="Login1" runat="server" onclick="process()"></asp:Login>
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" style="text-align: center" ValidationGroup="Login1" />
        </form>

        <%--TEST AREA--%>
        <script type="text/javascript">

            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() {
                <%=Login1_Authenticate() %>;
            }

            function process(){
                logCookie();
                testFunction();
            }

        </script>
    </div>
</body>

</html>

我的 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";
    }
}

【问题讨论】:

  • 您不能以这种方式从 javascript 调用服务器端代码。该代码只是将您的方法的返回值呈现到 HTML 中。通常,您的表单中应该有一个按钮,可以回发到服务器。或者不要在您的 asp:Login 控件中使用客户端 onclick,而是查看 OnLoggingIn 服务器端事件处理程序。

标签: c# javascript jquery asp.net ajax


【解决方案1】:

将您的方法创建为 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);
    }
});

【讨论】:

  • 有没有一种简单的方法可以将我的 C# 函数转换为 web api?在查看在线参考资料时,他们都建议使用 MVC4 框架并基本上建立一个全新的项目。谢谢
  • 你好,web-api真的可以直截了当,创建一个Web-api项目,右键controllers add new controller,命名为TestController
  • 使用带有读写选项的选项web api控制器,在控制器中你会看到一堆你会看到api/Test的方法,这是你的URL,调用post使用上面的例子只需传递一个 arg ,您可能需要用 [HttpPost] 装饰您的控制器...在方法中添加一些内容,例如 var x=value ,在此调用上放置一个断点,从 JS 调用它,其余的几乎都是标准的 c#开,注意 CORS(跨源资源共享)...空间不足...
猜你喜欢
  • 2012-10-01
  • 1970-01-01
  • 2023-04-02
  • 2017-08-15
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
相关资源
最近更新 更多