Hi friends,
I see that most of us know Json in forums, but there are a lot of people that starts working with that and I create a simple example that show How Json work, and not only that, because with this example you can see in action the Model Binder that MVC3 have by default and in MVC2 we need to do some little more things.
For this example you need to add the library Json2 created by Douglas Crockford.
View:(Jquery)
<script src="../../Scripts/json2.js" type="text/javascript"></script>
<input type="button" onclick="javascript:JsonInAction()" value="Json" />
<div id="JsonResponse"></div>
<script language="javascript" type="text/javascript">
var data = [{ "lastName": "Orue", "firstName": "Esteban", "phones": [{ "type": "Mobile", "number": "(011) 4121-2121" },
{ "type": "Home", "number": "(011) 4123-4567"}]
},
{ "firstName": "Alejandro", "lastName": "Orue", "phones": [{ "type": "Mobile", "number": "(011) 4121-7777" },
{ "type": "Home", "number": "(011) 4121-9999"}]}];
function JsonInAction() {
$.ajax({
url: '/Home/CollectJsonData',
data: JSON.stringify(data),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
var divInsert = document.getElementById("JsonResponse");
divInsert.innerHTML = result;
},
error: function () {
alert("error");
}
});
}
Controller:
public ActionResult CollectJsonData(List<Person> person)
{
return Json(data: person[0].firstName.ToString());
}
Model:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public List<Phone> phones { get; set; }
}
public class Phone
{
public string type { get; set; }
public string number { get; set; }
}
Note: Add a breakPoint in the ActionResult and see that you have 2 Persons, here is the magic of the Model Binder, MVC3 knows with the Model Binder that you have a class Person and you are sending in the post 2 persons.
Hope that Help!
Happy Coding Friends!!
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.