+N Consulting, Inc.

Json serialization – RPC style in MVC

In a previous posting, I discussed replacing the stock MVC serializer used for the JsonResult exposed when you use the controller method Json(..) instead of View.

This was all find and dandy. But how – you may wonder – can I call actions that contain complex parameters? Do I need a special binder? Should I write my own?

The answer is mostly “no”. As Phil Hack blogged, the ASP.NET MVC framework already contains value providers that take care of that for you. All you need to do is ensure that your Javascript calls your action using some very specific header and mime types.

Here is a function that may help you

<script type="text/javascript">
var postToAction = function (sender) {
var json = $('textarea#' + sender.data).val();
$("textarea#myResponse").val('working...');
$.ajax({
url: document.location.href,
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var replyText = JSON.stringify(data);
$("textarea#myResponse").val(replyText);
}
});
};
</script>

The special sauce here is the dataType and contentType together with the POST method. The rest is pretty much how jQuery wants to be called.

On line 6 you will note that I’m POSTing to the same URL as the browser is on – you may want to fiddle with that.

We call this function by hooking up a button, something like:

$("button#myButtonId").click('myTextAreaWithJsonContent', postToAction);

In your own implementation you will no doubt compose some object in JavaScript, or create a Json object. In the code above, I’m simply using Json formatted string: Line 3 gets the value from a text area element. If you compose a complex object and want to send it, you will need to convert it into a Json string. jQuery 1.5.1 – which I happen to use – already contains this facility, JSON.stringify(x) would do the trick. You can see it here used on line 12, for the inbound response which I simply stringify and hydrate a response text area. But this is only demo code – you will wire up the success (and failure function- right?) to your own logic.

But back to the core issue: Yes, MVC supports submitting Json and hydrating my controller action, but how do I persuade it to use my custom chosen super duper serializer rather than the stock one?

The answer is: Create a custom ValueProviderFactory and instantiate your favorite serializer in there. A bit of inspection on the MVC source code on CodePlex.com reveals the stock implementation.

Here’s a modified version, which isolates the serialization in a clear way:

public class MyJsonValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (!controllerContext.HttpContext.Request.ContentType.StartsWith(
"application/json", StringComparison.OrdinalIgnoreCase))
{
return null;
}
object value = Deserialize(controllerContext.RequestContext.HttpContext.Request.InputStream);
if (value == null)
{
return null;
}
var bag = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
PopulateBag(bag, string.Empty, value);
return new DictionaryValueProvider<object>(bag, CultureInfo.CurrentCulture);
}

private static object Deserialize(Stream stream)
{
string str = new StreamReader(stream).ReadToEnd();
if (string.IsNullOrEmpty(str))
{
return null;
}
var serializer = new JavaScriptSerializer(new MySpecialTypeResolver());
return serializer.DeserializeObject(str);
}

private static void PopulateBag(Dictionary<string, object> bag, string prefix, object source)
{
var dictionary = source as IDictionary<string, object>;
if (dictionary != null)
{
foreach (var entry in dictionary)
{
PopulateBag(bag, CreatePropertyPrefix(prefix, entry.Key), entry.Value);
}
}
else
{
var list = source as IList;
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
PopulateBag(bag, CreateArrayItemPrefix(prefix, i), list[i]);
}
}
else
{
bag[prefix] = source;
}
}
}

private static string CreatePropertyPrefix(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
{
return (prefix + "." + propertyName);
}
return propertyName;
}

private static string CreateArrayItemPrefix(string prefix, int index)
{
return (prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]");
}
}

It all really boils down to the same ceremony as the default implementation, except on the line
var serializer = new JavaScriptSerializer(new MySpecialTypeResolver()); lets to use our own special serializer. Woot!

To use this instead of the built in one, you will modify your global.asax.cs Application_Start() to include something like

var existing = ValueProviderFactories.Factories.FirstOrDefault(f => f is JsonValueProviderFactory);

if (existing != null)
{
ValueProviderFactories.Factories.Remove(existing);
}

ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());

where the built in one gets removed and my custom one gets added. Pretty straightforward.

With this technique and the one described in my previous post, you are ready to use the full power of MVC as an API supporting a nice strongly typed parameter for the back end developer and supporting fully customizable JSON in and out of methods. No real need for other frameworks or technologies for the serving jQuery needs.

Depending on your methods, you may even get away with one set of actions serving both form posts and jQuery invocation.

Happy coding!

Notice

We use cookies to personalise content, to allow you to contact us, to provide social media features and to analyse our site usage. Information about your use of our site may be combined by our analytics partners with other information that you’ve provided to them or that they’ve collected from your use of their services. You consent to our cookies if you continue to use our website.