Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Json With Jquery MVC2 and Model Binder

0.00/5 (No votes)
12 Jul 2011 1  
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

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

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 posted

var 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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here