Hi Friends,
In this article I will show the magic of Json and with a plus, the Model Binder that we know that MVC3 have by default, This is a simple example but I know that you guys will play with that a lot.
For this example you need to add the library Json2 created by Douglas Crockford
and these references: System.Reflection and System.Web.Script.Serialization for the Model Binder.
View:(Jquery Code)
<
input type="button" value="Come on Json" onclick="javascript:ComeOnJson()" id="jsonResult" />
<
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": "Sensei", "lastName": "Miyagi", "phones": [{ "type": "Mobile", "number": "(011) 4121-7777" },{ "type": "Home", "number": "(011) 4121-9999"}]
}];
function ComeOnJson(){
alert(JSON.stringify(data));
$.ajax({
url: '/Home/CollectJsonData',
data: JSON.stringify(data),
type: 'POST', contentType: 'application/json; charset=utf-8',
dataType:
'json', success: function (result) {
alert(result
);
},
error: function () {
alert("error");
}
});
}
</script>
Controller:
[
HttpPost]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; }
}
Model Binder:
using
System.Reflection;
using
System.Web.Script.Serialization;
public
class JsonModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (!IsJSONRequest(controllerContext))
{
return base.BindModel(controllerContext, bindingContext);
}
// Get the JSON data that's been postedvar request = controllerContext.HttpContext.Request;
var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();
return new JavaScriptSerializer()
.Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
}private static bool IsJSONRequest(ControllerContext controllerContext)
{
var contentType = controllerContext.HttpContext.Request.ContentType;return contentType.Contains("application/json");
}
}
public static class JavaScriptSerializerExt
{
public static object Deserialize(this JavaScriptSerializer serializer, string input, Type objType)
{
var deserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
return deserializerMethod.Invoke(serializer,new object[] { serializer, input, objType, serializer.RecursionLimit });
}
}
Global.asax:
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
RegisterRoutes(
RouteTable.Routes);
}
Hope That Help you guys!
Good Luck!