views:

64

answers:

1

I have an ASP.NET MVC server app and client code which uses jquery. I'd like to use ajax to transfer objects from client to server and back. On the server, I'd basically just be validating and serializing them. On the client, I have some UI code to create a visual representation and some other code to manage some object properties.

My question is this: what is the best way for me to marshal these objects around? My current idea is just to pass back an object wrapped as a JsonResult from my controller action, but I'm not sure of the best way to pass an object back into the MVC world after I'm done working with it on the client. I could just build a JSON string and pass it back into MVC as a string argument on a controller action, where I'd have to manually unpack the JSON into a .NET type. Is there a way to do a more automatic mapping into a .NET type, or some other "convenience" mechanism that could help prevent errors here (even if I have to write that convenience mechanism)?

This seems very similar to the ModelBinder idea, and maybe I'm just thrown by the idea that I intend to use jquery to push JSON back to the server rather than having a "regular" form post. Could I use a ModelBinder in some way to convert my client-provided JSON into a happy model type on the .NET side?

+5  A: 

You do NOT have to manually unpack the JSON into a .NET type. You've got various libraries that do this for you. I personally prefer JSON.NET. All you'd have to do is something like this:

var deserializedObject = JsonConvert.DeserializeObject<ObjectType>(json);

If you don't want a dependency on a third party library, just use Microsoft's JavaScriptSerializer:

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var deserializedObject = serializer.Deserialize<ObjectType>(json);

Microsoft's documentation for JavaScriptSerializer

Praveen Angyan