调用JS与C#方法 [英] Call C# Method with JS

查看:161
本文介绍了调用JS与C#方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个动态的变化基于用户属性,特别是一个用户名和角色登录到一个cookie登录页面。登录工作正常;但是,因为我使用的是真正迂回的方式调用C#函数,当我的JavaScript方法被调用,它包含了内嵌C#调用,它将跳过该方法中的所有其它线路的code和顺利,对于C#功能

我已经读到了要对这个更好的办法是使用的Webmethods和jQuery阿贾克斯,但是,我不能在我的C#文件中声明webMethods的。

我的前端看起来像下面的

的Login.aspx

 <%@页面语言=C#AutoEventWireup =真正的codeFILE =Login.aspx.cs继承=登录%>

!< D​​OCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
<头=服务器>
    <冠军> PAM测试< /标题>
    <链接相对=样式类型=文/ CSS的href =样式/ Site.css/>
    <脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/jquery-1.11.1.min.js>< / SCRIPT>
    <脚本类型=文/ JavaScript的SRC =脚本/ JScript.js>< / SCRIPT>
< /头>
<身体GT;
    < D​​IV ID =大旗> PAM测试工具< / DIV>
    < D​​IV ID =内容>
        <表格ID =Form1的=服务器的风格=保证金左:25%;文本对齐:中心;高度:41px;宽度:292px;>
            <% - 登录ASP对象 - %>
            < ASP:登录ID =Login1=服务器的onclick =过程()>< / ASP:登录>
            < ASP:的ValidationSummary ID =ValidationSummary1=服务器的风格=文本对齐:中心ValidationGroup =Login1/>
        < /形式GT;

        <% - 试验区 - %>
        <脚本类型=文/ JavaScript的>

            功能logCookie(){
                。的document.cookie =用户=+的document.getElementById(Login1_UserName)的价值; //这是用户名输入栏的ID,一旦显示在浏览器
            }

            功能testFunction(){
                &其中;%= Login1_Authenticate()%取代;
            }

            功能过程(){
                logCookie();
                testFunction();
            }

        < / SCRIPT>
    < / DIV>
< /身体GT;

< / HTML>
 

我的C#code看起来像这样

Login.aspx.cs

 使用系统;
使用System.Data这;
使用System.Data.SqlClient的;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;
使用的System.EnterpriseServices;

公共部分类登录:System.Web.UI.Page
{
    INT状态;
    INT的作用;
    SqlConnection的康涅狄格州;
    SqlCommand的命令;
    SqlDataReader的阅读器;


    保护字符串Login1_Authenticate()
    {

        //创建一个开放的连接
        康恩=
            新的SqlConnection(数据源= XXX;
            +初始目录= XXX;
            +用户ID = XXX;密码= XXX);

        conn.Open();

        //用户名字符串;
        //的userName = Convert.ToString(到Console.ReadLine());


        //创建一个SqlCommand对象此连接
        命令= conn.CreateCommand();
        command.CommandText =EXEC dbo.SP_CA_CHECK_USER @USER_ID ='+ Login1.UserName +',@PASSWORD ='+ Login1.Password +';
        command.CommandType = CommandType.Text;

        //执行返回一个SqlDataReader命令
        读者= Command.ExecuteReader却();

        //显示结果
        而(reader.Read())
        {
        状态= reader.GetInt32(0);
        }

        //关闭第一个读者
        reader.Close();

        // ----------
        existTest();
        返回登录过程完成;

    }


    公共静态字符串的GetData(INT用户ID)
    {
        / *如果需要,可以在这里做数据库操作* /
        回到我的用户ID为+ userid.ToString();
    }

    公共字符串existTest()
    {
        如果(状态== 0)
        {
            //登录
            会议[用户ID] = Login1.UserName;



            command.CommandText =EXEC dbo.SP_CA_RETURN_USER_ROLE @USER_ID ='+ Login1.UserName +';
            读者= Command.ExecuteReader却();
            而(reader.Read())
            {
                角色= reader.GetInt32(0);
            }

            会话[roleID] =作用;

            如果(会话[用户ID]!= NULL)
            {
                字符串userid =(字符串)(会话[用户ID]);
                //字符串roleID =(字符串)(会话[roleID]);
            }
            的Response.Redirect(Home.aspx);
        }
        其他
        {
            //错误的用户名/密码
        }



        //关闭连接
        reader.Close();
        conn.Close();
        返回处理完毕;
    }
}
 

解决方案

创建你的方法作为Web服务(Web的API是好的),然后使用JS AJAX调用它,这是我用网络API和JS用一个例子(这是发布数据,用得到,如果你有什么可张贴)

  $。阿贾克斯({
    键入:邮报,
    的contentType:应用/ JSON的;字符集= UTF-8,
    网址://本地主机:38093 / API /加/,//方法名
    数据:JSON.stringify({someVar:someValue中,someOtherVar:someOtherValue'}),
    数据类型:JSON,
    成功:someFunction(),//回调以上
    错误:函数(MSG){
        警报(msg.responsetext);
    }
});
 

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

解决方案

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

这篇关于调用JS与C#方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆