views:

412

answers:

1

I am following the accepted answer of ASP.NET MVC How to pass JSON object from View to Controller as Parameter. Like the original question, I have a simple POCO.

Everthing works fine for me up until the DataContractJsonSerializer.ReadObject method. I am getting the following exception:

Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

 Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
    If filterContext.HttpContext.Request.ContentType.Contains("application/json") Then
        Dim s As System.IO.Stream = filterContext.HttpContext.Request.InputStream

        Dim o = New DataContractJsonSerializer(RootType).ReadObject(s)

        filterContext.ActionParameters(Param) = o
    Else
        Dim xmlRoot = XElement.Load(New StreamReader(filterContext.HttpContext.Request.InputStream, filterContext.HttpContext.Request.ContentEncoding))
        Dim o As Object = New XmlSerializer(RootType).Deserialize(xmlRoot.CreateReader)
        filterContext.ActionParameters(Param) = o
    End If
End Sub

Any ideas?

+3  A: 

you might have to make sure you apply the [DataContract] and [DataMember] attributes on your poco.

As a separate option, you might want to consider this extension method which I wrote for the mvc ControllerContext:

using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public static class MvcExtensions
{
    public static T DeserializeJson<T>(this ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var form = context.RequestContext.HttpContext.Request.Form.ToString();
        return serializer.Deserialize<T>(HttpUtility.UrlDecode(form));
    }
}

It lets you easily deserialize json using the JavaScriptSerializer like this:

var myInstance = controllerContext.DeserializeJson<MyClass>();

Or, even simpler, you can make a generic model binder:

public class JsonBinder<T> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return controllerContext.DeserializeJson<T>();
    }
}

And then strongly type your mvc action method by applying this attribute to the poco class:

[ModelBinder(typeof(JsonBinder<MyClass>))]
Joel Martinez