4

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.

Pradeep Kalugade
  • 199
  • 3
  • 14
  • 1
    Well, it seems asp.net MVC automatically maps the incoming 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 Sep 27 '12 at 08:41

5 Answers5

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));
            }
          }
        );
Wahid Bitar
  • 13,776
  • 13
  • 78
  • 106
  • Implementing above results in following error 500 Internal Server Error Invalid JSON primitive: currSelectionData. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Invalid JSON primitive: currSelectionData. – Pradeep Kalugade Sep 27 '12 at 06:25
  • 1
    Then try to make it like this : data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" } For more information look at this http://stackoverflow.com/questions/2445874 – Wahid Bitar Sep 27 '12 at 06:37
  • data: { currSelectionData: JSON.stringify(currSelection)} – Xordal Sep 28 '12 at 10:22
1

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.

Joei Huang
  • 66
  • 5
0

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.

STO
  • 10,390
  • 8
  • 32
  • 32
  • -you are right! I expect the whole string to be received as parameter. Also I don't want any mapping between incoming string and existing objects. The entire incoming string needs to be saved in databse (In JSON format). Could you please guide further about alternatives you have suggested. – Pradeep Kalugade Sep 27 '12 at 06:33
0

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

Rajpurohit
  • 1,951
  • 2
  • 16
  • 19
0

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

Viktor Georgiev
  • 239
  • 1
  • 3
  • 7