简体   繁体   中英

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. Below is the CS file.

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

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('');'

Thanks

If the user provides all the information and clicks something(any control), you can make an ajax request from jquery. If you are returning some error message from CS, you can use that message directly as

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

d = "string which you retrun from CS".

where response is the parameter for your success function. d is the default property(variable) for the received object.

if you dont want to display string directly, use the returned data and call another javascript function.

Thanks

user1502890,

Server-side

I don't really know C# but it appears that you are trying to build a JSON string directly. 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. I guess this must be possible in 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:

$(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. The ternary alternaive to if(){...} else{...} also makes for compact code.

  • 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.

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.

If you are intrested in the PageMethods option, here is a quite good and easy tutorial .

I finally wrote : CS file as

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 :

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 ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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