Click here to Skip to main content
15,885,056 members
Articles / Data
Article

Json With Jquery MVC2 and Model Binder

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL2 min read 9.4K   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
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.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --