c# - 使用 JS 调用 C# 方法

标签 c# javascript jquery asp.net ajax

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

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

我的前端如下所示

登录.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";
    }
}

最佳答案

将您的方法创建为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# - 使用 JS 调用 C# 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24685973/

相关文章:

c# - 使用异步数据读取器

javascript - 检测 iframe 何时有响应?

javascript - 如何选择最后一行文本的第一个单词? (<h1> - <h6>, <p> 元素)

C# - SIP 控制

c# - ASP.NET + C# 多项目解决方案。我应该在哪里放置我的全局效用函数?

javascript - 如何一次又一次地动态替换文本

javascript - jQuery $('element' , this) 选择器,什么意思?

jQuery UI 自动完成刷新数据

c# - 更改 itextsharp 的字体大小

asp.net - 如何从 Javascript 将 TableRow/TableCell 添加到 ASP.NET 表?