ℙℕℤℝ 2014-07-10 20:45
浏览 166

用JS调用C#方法

I am trying to create a login page that changes dynamically based on user attributes, specifically a username and role that is logged into a cookie. The login works fine; however, because I am using a really round-about way of calling C# functions, when my javascript method is called that contains the inline C# call, it skips all other lines of code in that method and goes right for the C# function.

I have read that a better way of going about this is the use of Webmethods and JQuery Ajax, however, I am unable to declare webmethods in my C# file.

My front end looks like the following

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>

My C# code looks like this

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";
    }
}
  • 写回答

1条回答 默认 最新

  • weixin_33711647 2014-07-10 21:44
    关注

    Create your method as a web-service (web-api is good) then call it using jS ajax, here's an example i use with web-api and JS (this is posting data, use get if you have nothing to post)

    $.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);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?