Monthly Archives: May 2009

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