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?
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>))]
May not be appropriate to this question, but this helped me and might help others with this exception - try resetting your stream before reading it.
s.Position = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With