Pages

Wednesday, September 5, 2012

How to post a complex object via AJAX to an MVC Action

I needed to post an object from Javascript to an Action using Asp.Net Mvc, and realized it is not as straitghforward as I thought it would be. So, I put together a little example which can be used for reference in the future.

First, let's create a PersonModel object in C#:

This is the same object that I want to later on, post from the client side to an MVC Action in my controller. Now, let's see the Controller action accepting a PersonModel parameter:

Inside the Controlles action you will do whatever your business dictates. In my case I am just receiving the PersonModel object, obtaining the HTML representation of a Partial View receiving the PersonModel, and returning that HTML back to the UI in json format. Finally the Html code, showing a <div> element where the content comming back from the server will be displayed. Also a button that calls the javascript function showPerson(). The function creates a personModel in javascript and assigns arbitrary values to the Name and Age fields.


Important points to consider here:

1- You need to send your content as json type in the $.ajax request.
2- You need to somehow flatten your data to json format, which I'm doing using JSON.stringify

Until here, it all looks good, however, your Controller action will only receive a PersonModel with empty fields. That's because MVC doesn't know how to turn your json object into a C# PersonModel. In order to make that piece work, you need to go to your Global.asax, and in the Application_Start function add this line of code:



You will need to use the System.Mvc.Web.dll for this purpose. I hope this helps.
Download sample code of the project

No comments:

Post a Comment