我遵循 ASP.NET MVC How to pass JSON object from View to Controller as Parameter的接受答案.就像原始问题一样,我有一个简单的POCO. 在DataContractJsonSerializer.ReadObject方法之前,Everthing对我来说很好.我收到以
在DataContractJsonSerializer.ReadObject方法之前,Everthing对我来说很好.我收到以下异常:
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
有任何想法吗?
您可能必须确保在poco上应用[DataContract]和[DataMember]属性.作为一个单独的选项,您可能需要考虑我为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)); } }
它允许您使用JavaScriptSerializer轻松反序列化json,如下所示:
var myInstance = controllerContext.DeserializeJson<MyClass>();
或者,甚至更简单,您可以制作通用模型绑定器:
public class JsonBinder<T> : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { return controllerContext.DeserializeJson<T>(); } }
然后通过将此属性应用于poco类来强烈键入您的mvc操作方法:
[ModelBinder(typeof(JsonBinder<MyClass>))]