user5120455
user5120455

Reputation: 141

Passing JSON to MVC Controller?

I have a JSON object with nested arrays which I would like to send to a controller.

This is my jQuery.ajax call:

$.ajax({
            url: "@Url.Action("ExportJson")",
            type: "POST",
            data: JSON.stringify(myObj),
            contentType:"application/json",
            success: function (result) {

            }
        });

Controller:

public ActionResult ExportJson(string json)
            {



                return null;
            }

Why is the json string coming back as null in the controller? Whereas console.log(JSON.stringify(myObj)) shows the correct object in browser console.

Upvotes: 1

Views: 28570

Answers (2)

DragoRaptor
DragoRaptor

Reputation: 735

Try This -

Consider the following JSON data. Let's assume that the json data is obtained from the whatever form you're trying to submit.

var jsonData =  {"FirstName":"John", "LastName":"Doe", "DoB":"01/01/1970", 
                  [{"CompanyName":"Microsoft", "StartDate":"01/01/2010", "EndDate":"01/01/2011"},                      
                   {"CompanyName":"Apple Inc", "StartDate":"01/01/2011", "EndDate":"01/01/2012"}
                ]};

The below ajax method should get you going. Make sure you specify POST type, as ajax method uses GET method by default.

$.ajax({
  url:"@Url.Action("ExportJson")",
  data: jsonData, //this could also be form data
  type:"POST",
  success:function(data){
     //Do something:
  }})
  .done(function(data){
    //data - response from server after save
  })
  .fail(){
    alert("ajax error")
  });

MVC Controller: Decorate the Action method with HttpPost verb. This action method will only handle http post request from browser. Ajax submission from the browser will be automatically deserialized to FormData c# class as a poco. As a result you should be able to consume the jsnData object without any modifications.

[HttpPost]
public ActionResult ExportJson(FormData jsnData)
{
     //do something here
}

FormData class would be C# class representing the json data:

public class FormData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DoB { get; set; }
    public List<WorkExperience> workExperience { get; set; }
}

public class WorkExperience 
{
   public string CompanyName { get; set;}
   public DateTime StartDate { get; set; }
   public DateTime EndDate { get; set; }       
} 

Upvotes: 1

Serhat MERCAN
Serhat MERCAN

Reputation: 1098

Change the ajax post like this;

$.ajax({
        url: "@Url.Action("ExportJson")",
        type: "POST",
 //************************************
        data: {"json" : JSON.stringify(myObj)},
 //************************************
        contentType:"application/json",
        success: function (result) {

        }
    });

Upvotes: 0

Related Questions