最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Posting JSON string to ASP.NET MVC 3 action results in null parameter - Stack Overflow

programmeradmin2浏览0评论

I am posting a JSON string to asp MVC as follows.

AJAX call

$.ajax({
            type: "POST",
            url: "@(storeLocation)IDR/OpcInsertCustomerProfile/",
            data: JSON.stringify(currSelection),
            contentType: "application/json",
            success: function(data) {
              alert('success : ' + JSON.stringify(data));
            },
            error: function(data) {
             alert('Error : ' + JSON.stringify(data));
            }
          }
        );

In the controller:

[HttpPost]
        [ActionName("OpcInsertCustomerProfile")]
        public JsonResult OpcInsertCustomerProfile(string currSelectionData)
        {
            try
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                var res = ser.Serialize(currSelectionData);
                return Json(currSelectionData, JsonRequestBehavior.AllowGet);

            }
            catch (Exception exc)
            {
                return Json(new { error = 1, message = exc.Message });
            }
        }

Debugger indicates the action gets called successfully, however the ining string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as ining parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.

I am posting a JSON string to asp MVC as follows.

AJAX call

$.ajax({
            type: "POST",
            url: "@(storeLocation)IDR/OpcInsertCustomerProfile/",
            data: JSON.stringify(currSelection),
            contentType: "application/json",
            success: function(data) {
              alert('success : ' + JSON.stringify(data));
            },
            error: function(data) {
             alert('Error : ' + JSON.stringify(data));
            }
          }
        );

In the controller:

[HttpPost]
        [ActionName("OpcInsertCustomerProfile")]
        public JsonResult OpcInsertCustomerProfile(string currSelectionData)
        {
            try
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                var res = ser.Serialize(currSelectionData);
                return Json(currSelectionData, JsonRequestBehavior.AllowGet);

            }
            catch (Exception exc)
            {
                return Json(new { error = 1, message = exc.Message });
            }
        }

Debugger indicates the action gets called successfully, however the ining string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as ining parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.

Share Improve this question asked Sep 27, 2012 at 6:14 Pradeep KalugadePradeep Kalugade 1993 silver badges14 bronze badges 1
  • 1 Well, it seems asp MVC automatically maps the ining JSON object to individual objects. This is interesting, but I need to capture the entire json object as SINGLE STANDALONE STRING. How do I do this? – Pradeep Kalugade Commented Sep 27, 2012 at 8:41
Add a ment  | 

5 Answers 5

Reset to default 3

Try this :

$.ajax({
            type: "POST",
            url: "@(storeLocation)IDR/OpcInsertCustomerProfile/",
            data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" },
            contentType: "application/json",
            success: function(data) {
              alert('success : ' + JSON.stringify(data));
            },
            error: function(data) {
             alert('Error : ' + JSON.stringify(data));
            }
          }
        );

One way is to allow the action to receive the parameter as POST data instead of JSON "Stringified" data. To do that, post the data without JSON.Stringify. Hopefully this is what you need.

If not you might want to try creating an object just to receive this simple data.

Look at your action method: is it correct that method accepts string with serialized JSON, than serialized that string as JSON again and then dismiss the result and serializes and returns the same string again?

If you send request with application/json type ASP.NET MVC tries to deserialize received string and bind it to action parameters: in your case it tries to find property currSelectionData inside your JSON object. Is that property exists? Maybe you expect whole string is received as currSelectionData parameter? Then you need to use FormCollection or Request.Form instead because default model binder does not support this.

Actually i fill my state dropdown in selection of country with json i do like this

in my controller i have action it's return my data in json format like this it's below

public JsonResult State(int countryId)
        {               
            var stateList = CityRepository.GetList(countryId);
            return Json(stateList, JsonRequestBehavior.AllowGet);
        } 

in my view

<script type="text/javascript">
    function cascadingdropdown() {
        $("#stateID").empty();
        $("#stateID").append("<option value='0'>--Select State--</option>");
        var countryID = $('#countryID').val();
        $.ajax({
            url: "/City/State",
            dataType: 'json',
            data: { countryId: countryID },
            success: function (data) {
                $("#stateID").empty();
                $("#stateID").append("<option value='0'>--Select State--</option>");
                $.each(data, function (index, optiondata) {
                    alert(optiondata.StateName);
                    $("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
                });
            },
            error: function () {
                alert('Faild To Retrieve states.');
            }

        });
    } 
</script>

i think this will help you...

When sending json through Ajax, I think this is the right approach for the data property in Ajax: data: "{'parameterNameInAction':'" + JSON.stringify(jsonData) + "'}"

发布评论

评论列表(0)

  1. 暂无评论