anevil
anevil

Reputation: 847

JSON pass null value to MVC 4 controller in IE9

I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9

The JavaScript :

var newCustomer = {
    CustName: $("#CustName").val(),
    CustLocalName: $("#CustLocalName").val(),
    CustNumber: $("#CustNumber").val(),
    CountryID: $("#SelectCountry").val(),
    City: $("#City").val()
};

$.ajax({
     url: '@Url.Content("~/CustomerHeader/CreateCustomerHeader")',
     cache: false,
     type: "POST",
     dataType: "json",
     contentType: 'application/json; charset=utf-8',                     
     data: JSON.stringify(newCustomer),
     success: function (mydata) {
         $("#message").html("Success");
     },
     error: function () {
         $("#message").html("Save failed");
     }
});

and this is my controller :

public JsonResult CreateCustomerHeader(CustomerHeader record)
{
    try
    {
        if (!ModelState.IsValid)    
        {
            return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct   it and try again." });
        }

        RepositoryHeader.Update(record);

        return Json(new { Result = "OK", Record = record});
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.

UPDATE : New method trying using $.post

function CreateNewCustomer(newCustomer) {
    $.post("/CustomerHeader/CreateCustomerHeader",
      newCustomer,
      function (response, status, jqxhr) {
          console.log(response.toString())
      });
}

Upvotes: 2

Views: 2331

Answers (2)

Tieson T.
Tieson T.

Reputation: 21191

Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):

var data = {
    CustName: $("#CustName").val(),
    CustLocalName: $("#CustLocalName").val(),
    CustNumber: $("#CustNumber").val(),
    CountryID: $("#SelectCountry").val(),
    City: $("#City").val()
};

$.post({
    '@Url.Action("CreateCustomerHeader", "CustomerHeader")',                  
    data,
    function(response, status, jqxhr){
        // do something with the response data
}).success(function () {
    $("#message").html("Success");
}).error(function () {
    $("#message").html("Save failed");
});

$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.

response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.

Upvotes: 2

anevil
anevil

Reputation: 847

first of all I would like to apologize @Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.

The full script :

try{ ..

    var newCustomer =
                {
                    CustName: $("#CustName").val(),
                    CustLocalName: $("#CustLocalName").val(),
                    CustNumber: $("#CustNumber").val(),
                    CountryID: $("#SelectCountry").val(),
                    City: $("#City").val()
                };


             $.ajax({                 
                 url: '/CustomerHeader/CreateCustomerHeader',
                 cache: false,
                 type: "POST",
                 dataType: "json",
                 data: JSON.stringify(newCustomer),
                 contentType: "application/json; charset=utf-8",                 

                 success: function (mydata) {
                     $("#message").html("Success");
                 },
                 error: function () {
                     $("#message").html("Save failed");
                 }
             });

             }

             catch(Error) {
                 console.log(Error.toString());
             }

             //$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!

I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.

Thanks for all the efforts in solving my problem guys :-)

Upvotes: 0

Related Questions