简体   繁体   English

如何将CS文件中的json变量传递给Javascript函数?

[英]How to pass a json variable from a CS file to an Javascript function?

I have a method in C#, which creates a JSON object of the user credentials. 我在C#中有一个方法,该方法创建用户凭证的JSON对象。 Below is the CS file. 以下是CS文件。

public string CreateLoginjson(string strErrorType, bool blIsAuthenticated)
{
    StringBuilder sbLoginJson = new StringBuilder();
    if (blIsAuthenticated)
    {
        sbLoginJson.Append("{LoginSuccess:1");
    }
    else
    {
        sbLoginJson.Append("{LoginSuccess:0");
    }

    if (strErrorType != string.Empty)
    {
        if (strErrorType.TrimEnd(new char[] { ',' }) == "Token" ||
                strErrorType.TrimEnd(new char[] { ',' }) == "BlankToken")
        {
            sbLoginJson.Append(",txtTestTokenNumber1:\"Error\"");
            sbLoginJson.Append(",txtTestTokenNumber2:\"Error\"");
            sbLoginJson.Append(",txtTestTokenNumber3:\"Error\"");
            sbLoginJson.Append(",txtTestTokenNumber4:\"Error\"");

        }


        if (strErrorType.TrimEnd(new char[] { ',' }) == "Password")
        {
            sbLoginJson.Append(",txtPassword:\"Error\"");

        }

        if (strErrorType.TrimEnd(new char[] { ',' }) == "UserName")
        {
            sbLoginJson.Append(",UserName:\"Error\"");

        }
        string strLoadErrorControlMessage = LoadErrorControl(strErrorType,
                string.Empty);

        if (strLoadErrorControlMessage!= string.Empty)
        {
            sbLoginJson.Append(",ErrorMessage:
            '" + strLoadErrorControlMessage + "'");
        }
    }
    sbLoginJson.Append("}");

    var LoginJson = sbLoginJson.ToString();
    return LoginJson;
}

Now, I need to pass the LoginJson to a JS function that checks if incorrect credentials are provided, this function finds the control & adds an attribute to it JS 现在,我需要将LoginJson传递给JS函数,该函数检查是否提供了不正确的凭据,该函数查找控件并向其中添加属性

function GetLoginJson(strLoginJson) {
    if (strLoginJson != '' && strLoginJson != undefined) {
        var objLoginJson = strLoginJson;

        if (objLoginJson.LoginSuccess == "1") {

        }
        else if (objLoginJson.LoginSuccess == "0") {

            if (objLoginJson.txtUserName != '' 
                 && objLoginJson.txtUserName != undefined) 
            {
                $('#txtUserName').attr("class", objLoginJson.txtUserName);
            }
            else 
            {
                $('#txtUserName').attr("class", "Input");
            }

            if (objLoginJson.txtPassword != '' 
                 && objLoginJson.txtPassword != undefined) 
            {
               $('#txtPassword').attr("class", objLoginJson.txtPassword);
            }
            else 
            {
                $('#txtPassword').attr("class", "Input");
            }
            if (objLoginJson.txtTestTokenNumber1 != '' 
                  && objLoginJson.txtTestTokenNumber1 != undefined) 
            {
                $('#txtTestTokenNumber1').attr("class", 
                                                objLoginJson.txtTestTokenNumber1);
            }
            else 
            {
                $('#txtTestTokenNumber1').attr("class", "Error");
            }
            if (objLoginJson.txtTestTokenNumber2 != '' 
                  && objLoginJson.txtTestTokenNumber2 != undefined) 
            {
               $('#txtTestTokenNumber2').attr("class", 
                                               objLoginJson.txtTestTokenNumber2);
            }
            else 
            {
                $('#txtTestTokenNumber2').attr("class", "Error");
            }

            if (objLoginJson.txtTestTokenNumber3 != '' && 
                 objLoginJson.txtTestTokenNumber3 != undefined) {
                $('#txtTestTokenNumber3').attr("class", 
                                                objLoginJson.txtTestTokenNumber3);
            }
            else 
            {
                $('#txtTestTokenNumber3').attr("class", "Error");
            }
            if (objLoginJson.txtTestTokenNumber4 != '' && 
                  objLoginJson.txtTestTokenNumber4 != undefined) {
                $('#txtTestTokenNumber4').attr("class", 
                                                objLoginJson.txtTestTokenNumber4);
            }
            else 
            {
                $('#txtTestTokenNumber4').attr("class", "Error");
            }

            $('#ErrorControl').html('');

        }
    }
}

I want to pass the JSON variable from the CS to this jQuery statement `$('#ErrorControl').html('');' 我想将CS中的JSON变量传递给此jQuery语句$('#ErrorControl')。html('');'

Thanks 谢谢

If the user provides all the information and clicks something(any control), you can make an ajax request from jquery. 如果用户提供所有信息并单击某些东西(任何控件),则可以从jquery发出ajax请求。 If you are returning some error message from CS, you can use that message directly as 如果要从CS返回一些错误消息,则可以将该消息直接用作

$('#ErrorControl').html(response.d) $('#ErrorControl')。html(response.d)

d = "string which you retrun from CS". d =“您要从CS重播的字符串”。

where response is the parameter for your success function. 其中,响应是成功功能的参数。 d is the default property(variable) for the received object. d是接收对象的默认属性(变量)。

if you dont want to display string directly, use the returned data and call another javascript function. 如果您不想直接显示字符串,请使用返回的数据并调用另一个javascript函数。

Thanks 谢谢

user1502890, 用户1502890,

Server-side 服务器端

I don't really know C# but it appears that you are trying to build a JSON string directly. 我不太了解C#,但您似乎正在尝试直接构建JSON字符串。 It is far more normal (and easier and more reliable) to build an object and then to stringify it into JSON with either a built-in language command or a utility method. 构造一个对象,然后使用内置语言命令或实用程序方法将其字符串化为JSON,这是更正常(更简便,更可靠)的方法。 I guess this must be possible in C#. 我想这在C#中一定是可能的。

Client-side 客户端

Assuming the credentials fields to be in a form with id="credentialsForm" and the server-side script to be requestable as the relative URL "myCredentialsChecker.xtn", then the jQuery will be something like this: 假设凭据字段采用id="credentialsForm"的形式,并且服务器端脚本可作为相对URL“ myCredentialsChecker.xtn”请求,则jQuery将如下所示:

$(function() {
    function loginResponse(j) {
        j = j || {};
        if (j.LoginSuccess) {
            //...
        }
        else {
            $('#txtUserName').attr("class", j.txtUserName ? j.txtUserName : "Input");
            $('#txtPassword').attr("class", j.txtPassword ? j.txtPassword : "Input");
            $('#txtTestTokenNumber1').attr("class", j.txtTestTokenNumber1 ? j.txtTestTokenNumber1 : "Error");
            $('#txtTestTokenNumber2').attr("class", j.txtTestTokenNumber2 ? j.txtTestTokenNumber2 : "Error");
            $('#txtTestTokenNumber3').attr("class", j.txtTestTokenNumber3 ? j.txtTestTokenNumber3 : "Error");
            $('#txtTestTokenNumber4').attr("class", j.txtTestTokenNumber4 ? j.txtTestTokenNumber4 : "Error");
            $('#ErrorControl').html('');
        }
    }

    $("#credentialsForm").on('submit', function() {
        $.ajax({
            url: "myCredentialsChecker.xxx",
            data: $(this).serialize(),
            type: 'POST', // or 'GET'
            dataType: 'json',
            success: function(j) {
                loginResponse(j);
            ),
            error: function() {
                loginResponse();
            }
        });
        return false;
    });
});

Notes 笔记

  • Everything in the else{...} clause simplifies as above because '' and undefined are both falsy, so simply testing foo will do the job. else{...}子句中的所有内容都如上所述进行了简化,因为''undefined都是虚假的,因此只需测试foo即可完成工作。 The ternary alternaive to if(){...} else{...} also makes for compact code. if(){...} else{...}的三进制替代也使代码紧凑。

  • I'm not convinced that setting classes to the returned strings is the right thing to do but I've not changed this aspect. 我不认为将类设置为返回的字符串是正确的做法,但是我没有改变这一方面。

First of all, you could try the JavaScriptSerializer (chekc the link) to serialize any object into JSON and then send a string response to the client. 首先,您可以尝试使用JavaScriptSerializer (链接该链接)将任何对象序列化为JSON,然后向客户端发送字符串响应。

For the communication between the server and the client you can use the jquery's ajax call which is calling your webservice (fe), or if you building an ASP.NET site or application then you can use PageMethods and calling it directly from javascript. 对于服务器和客户端之间的通信,您可以使用jquery的ajax调用来调用Web服务(fe),或者,如果您构建ASP.NET网站或应用程序,则可以使用PageMethods并直接从javascript调用它。

If you are intrested in the PageMethods option, here is a quite good and easy tutorial . 如果您对PageMethods选项很感兴趣,那么这里是一个很好而又简单的教程

I finally wrote : CS file as 我终于写了:CS文件为

public string CreateLoginjson(string strErrorType, bool blIsAuthenticated)
{
    StringBuilder sbLoginJson = new StringBuilder();
    if (blIsAuthenticated)
    {
        sbLoginJson.Append("{LoginSuccess:1");
    }
    else
    {
        sbLoginJson.Append("{LoginSuccess:0");
    }

    if (strErrorType != string.Empty)
    {
        if (strErrorType.TrimEnd(new char[] { ',' }) == "Token" || strErrorType.TrimEnd(new char[] { ',' }).Split(new char[] { ',' }).Contains("BlankToken"))
        {
            sbLoginJson.Append(",txtTestTokenNumber1:\"Error\"");
            sbLoginJson.Append(",txtTestTokenNumber2:\"Error\"");
            sbLoginJson.Append(",txtTestTokenNumber3:\"Error\"");
            sbLoginJson.Append(",txtTestTokenNumber4:\"Error\"");

        }

        if (strErrorType.TrimEnd(new char[] { ',' }) == "Password" ||  strErrorType.TrimEnd(new char[] { ',' }).Split(new char[] { ',' }).Contains("BlankPassword"))
        {
            sbLoginJson.Append(",txtPassword:\"Error\"");

        }

        if (strErrorType.TrimEnd(new char[] { ',' }) == "UserName" ||  strErrorType.TrimEnd(new char[] { ',' }).Split(new char[] { ',' }).Contains("BlankUserName"))
        {
            sbLoginJson.Append(",txtUserName:\"Error\"");
        }

        string strLoadErrorControlMessage = LoadErrorControl(strErrorType, string.Empty);

        if (strLoadErrorControlMessage != string.Empty)
        {
            PageTestApplicationLogin objPageTestApplicationLogin = new PageTestApplicationLogin(objClientConfiguration);
            sbLoginJson.Append(",ErrorMessage:'" + objPageTestApplicationLogin.GetTestApplicationLoginErrorHtml("", strLoadErrorControlMessage).Replace("'", "\"") + "'");
        }
        sbLoginJson.Append("}");
    }
    var LoginJson = sbLoginJson.ToString();
    return LoginJson;
}

JS file : JS文件:

if (objLoginJson.ErrorMessage != '' && objLoginJson.ErrorMessage != undefined) {
    $('#ErrorControl').html(objLoginJson.ErrorMessage);
    $('#ErrorControl').find('#tblLoginError').css('display', 'block');
}
else {
    $('#ErrorControl').html("");
    $('#ErrorControl').find('#tblLoginError').css('display', 'none');
}

Thank you all for your Suggestions.. Cheers .... 谢谢大家的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM