简体   繁体   中英

Passing JSON objet to Code Behind file

I have used ajax to pass the JSON object from javascript function to code behind file (.cs) in C# with the following code as follows:

 function buildProfile(user) {

            alert('user data');
            $.ajax({
                    type: 'POST',
                    url: '/Test.aspx/GetCity',
                    data: "{city:" + JSON.stringify(user) + "}",
                    //data: JSON.stringify(user),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (r) {
                        alert(r.d.Name);
                    }
                });
}

In the above code the control is going successfully to the Test.aspx.cs codebehind file to the method name " GetCity ".

Can I pass the JSON object to a user control rather than to a page? For example can I create a user control with name Test and change the url of the above code to : url: '/Test.ascx/GetCity', the code will become as follows:

 function buildProfile(user) {

            alert('user data');
            $.ajax({
                    type: 'POST',
                    url: '/Test.ascx/GetCity',
                    data: "{city:" + JSON.stringify(user) + "}",
                    //data: JSON.stringify(user),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (r) {
                        alert(r.d.Name);
                    }
                });
}

For now the control is not going to the user control Test.aspx.cs code behind file. Is it possible to pass the JSON object to a user control?

Any help will be greatly appreciated. Thanks in advance.

Not sure If I got your need right but I had a similar need a couple months ago and maybe this link can help (please see Ajith S Nair comment) : https://forums.asp.net/t/2022191.aspx?How+to+create+a+user+control+in+MVC .

If you combine his extension with something similar to your ajax code it might be your solution :

!function ($) {
"use strict";
$.ajax({
    type: "POST",
    url: "/ControllerName/MethodName",
    data: "{city:" + JSON.stringify(user) + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {//Success code},
    failure: function (response) {//Failure code},
    error: function (response) {//Error code}
})};

I hope it helps !

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