Pass JSON object from Javascript code to MVC controller

I made a lot of search to know how to pass JSON object from client code to MVC control. But I could not find any proper example or guide. So finally I made some research and I found that by serializing the JSON object using json.js, it is possible to send serialized data to MVC control from client side.

Let me elaborate these steps:

1st it requires json.js included in your project.

In Step 1 I created an array of literals containing object literals. This is the client code with three fields’ id, name and email which we want to send to server. Step by step explanation on this structure could be found here.

In Step 2 we are serializing this object into a string with help of json library method $.toJSON().

In Step 3 we are sending this serialized data to MVC control action via AJAX post.

Step 1:
function SaveData() {
var dobj = [{ id: 1, name: 'ABCD', email: 'abcd@one.com' },
{ id: 2, name: 'EFGH', email: 'efgh@one.com' },
{ id: 3, name: 'IJKL', email: 'ijkl@one.com' },
{ id: 4, name: 'MNOP', email: 'mnop@one.com'}];

Step 2:
var jlst = $.toJSON(dobj);

Step 3:
$.post("/DistributionList/SaveMyData/", { jsonData: jlst },
function(data, textStatus) {
if (textStatus != "success") {
result = "false";
}
});
}

With this our client side task is complete.

Next is to consume this data at the server side, i.e. at MVC control.

At server control side we have an action which accepts string data. Serialized json object will be routed here. To deserialize this data you require an object of JavaScriptSerializer which is available in System.Web.Script.Serialization library.

Create a model class with excat number of fileds to hold the deserialized data.

public class PersonData
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
}

In the below code we have created an object of List of type Person to hold the multiple person information. With the help of JavaScriptSerializer object we are able to deserialize the JSON object.

public ActionResult SaveMyData(string jsonData)
{
bool result = true;
List<PersonData> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData= jss.Deserialize<List<PersonData>>(jsonData);

// DO YOUR OPERATION ON LIST OBJECT

return Content(result.ToString());
}

Conclusion: Hope this post would be helpful those who are find difficult to pass JSON data from client side to any server side control. If you find anything wrong or better way to do the thing please let me know.

UPDATE: JSONP made easy in ASP.NET AJAX

Advertisements

About Krishnaraj Barvathaya

I am Krishnaraj Barvathaya, a software developer from Bangalore and I primarily write on Microsoft Technologies and latest technical stuffs which interests me.

Posted on May 28, 2009, in .Net and tagged , , , , . Bookmark the permalink. 19 Comments.

  1. nice! i’m gonna make my own journal

  2. People differ in eye color and the differences are noticeable but nobody pays any serious heed to these differences. ,

  3. Introduce New Search Techniques. ,

  4. Thanks for this post, I’ve been searching for a clear explanation on how to do this for awhile now!

  5. Awesome! Thank you very much =)

  6. Thanks for sharing! I’ve been struggling with this for a while, until i found that the parameter name in the controller must match the key of json object that you pass.

  7. It’s really nice. could you provide this sample code. I am getting error in toJson method. unable to get js file.

  8. Great method it helped me a lot.

  9. Excellent work, the key here is $.post as opposed to me using $.getJSON.

    Thank you.

  10. Thanks it is very much

  11. Nice, thanks! Of all the articles I’ve read about this topic, this was one of the most clear and to-the-point. 15 minutes later, I was successfully posting my JSON object to my controller action. Arvind’s comment above is key, and you might want to add a note in the article around Step 3 that it’s important the name you give the key in the $.post needs to match the name of the string param to the Action method.

    Also, here’s a nice utility that makes quick work of generating C# classes that match your JSON object, so you don’t have to manually create your model class to hold the deserialized data: http://json2csharp.com . You might have to clean up the code it generates, but for complex models it speeds things up considerably.

    Thanks again!

  12. Vicente Rodríguez

    i have a very long time for server request, then i have a laaaaaarge object from external process, always, always i get an error 500 when i try to pass the c# objetc to javascript within serializer , what should i do? please, if somone have the answer, let me know pleassse hehe

  13. It is very helpful ,thanks

  14. Thanks a lot man!!! u just saved my day!! 🙂 keep sharing ur ideas 🙂 🙂

  15. Excellent, this helped me tonight!

  1. Pingback: ASP.NET MVC Archived Buzz, Page 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: