Pradeep Kalugade
Pradeep Kalugade

Reputation: 199

Posting JSON string to ASP.NET MVC 3 action results in null parameter

I am posting a JSON string to asp.net 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 incoming 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 incoming 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.

Upvotes: 4

Views: 6549

Answers (5)

Viktor Georgiev
Viktor Georgiev

Reputation: 249

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

Upvotes: 0

Joei Huang
Joei Huang

Reputation: 66

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.

Upvotes: 1

Wahid Bitar
Wahid Bitar

Reputation: 14094

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

Upvotes: 3

Rajpurohit
Rajpurohit

Reputation: 1991

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

Upvotes: 0

STO
STO

Reputation: 10648

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.

Upvotes: 0

Related Questions