Passing Json Objects to C# MVC Controllers via AJAX

The good ol’ days of Visual Basic 6, circa 1999.

It isn’t that much of a complex problem, being able to pass Javascript objects directly to C# MVC Controllers, but there are many aspects of the problem that are overlooked, which leaves developers stumped.

In most cases, either the developer finds an empty object when debugging their C# Controller method, or no object at all (null).

There is a solution to all this, and after running into all the caveats and finally coming out on top with a working example, I’d like to share my knowledge with the community.


Step #1, Send JSON via AJAX

Make sure the content you are sending is JSON formatted. Using jQuery, I set up my request like the following:

var data = {
companyId: 5,
people:[
{name:'Some Guy', age: 34, location: 'Las Vegas, NV 89128'},
{name:'Some Girl', age: 25, location: 'Seattle, WA 98145'}
]
};
$.ajax('/mycontroller/mymethod', {
method: 'post',
contentType: 'application/json',
data: JSON.stringify(data),
traditional: true,
success: function (d) {
//do stuff
}
});

The data object has two properties, named “companyId” & “people”, a number and an array of objects. In the next step, these two properties will be mapped to a C# Controller method argument list.

Notice that I used JSON.stringify to serialize my data object. Also, contentType is important, and I removed the property dataType. I don’t know if traditional:true made any difference, but someone on StackOverflow recommended using it, so there it is.


Step #2, Send Data To ASP.NET MVC

The data object has been serialized to JSON and sent to the server, so now we must prepare C# to handle the data object correctly.

First, I created a structure to capture the data object and bind the property values to my structure.

public struct myStruct{
public string name { get; set; }
public int age { get; set; }
public string location { get; set; }
}

The key mistake that I made early on was to create a structure without including { get; set; } for each property. This is one of those important caveats I overlooked. Also, you can use a class instead of a structure, but you must include { get; set; } for your class properties as well.

Next, I created the Controller method that will handle the AJAX request.

[HttpPost]
public ActionResult MyMethod(int companyId, List<myStruct> people){
//do stuff
}

That’s it! Just make sure you check all user input data for malicious content coming into the server , and you’ll have yourself a clean and straight-forward approach to developing solid web applications in ASP.NET.

Subscribe & stay tuned for more tips & tricks on C# MVC development, as well as .NET Core application development!

Sincerely,

Mark Entingh

Like what you read? Give Mark Entingh a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.