将JSON数据发布到ASP.NET MVC

将JSON数据发布到ASP.NET MVC,第1张

将JSON数据发布到ASP.NET MVC

看一下Phil Haack关于模型绑定JSON数据的文章。问题是默认模型联编程序无法正确序列化JSON。您需要某种ValueProvider或可以编写自定义模型绑定程序:

using System.IO;using System.Web.script.Serialization;public class JsonModelBinder : DefaultModelBinder {        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if(!IsJSonRequest(controllerContext)) {     return base.BindModel(controllerContext, bindingContext); } // Get the JSON data that's been posted var request = controllerContext.HttpContext.Request; //in some setups there is something that already reads the input stream if content type = 'application/json', so seek to the begining request.InputStream.Seek(0, SeekOrigin.Begin); var jsonStringData = new StreamReader(request.InputStream).ReadToEnd(); // Use the built-in serializer to do the work for us return new JavascriptSerializer()     .Deserialize(jsonStringData, bindingContext.Modelmetadata.ModelType); // -- REQUIRES .NET4 // If you want to use the .NET4 version of this, change the target framework and uncomment the line below // and comment out the above return statement //return new JavascriptSerializer().Deserialize(jsonStringData, bindingContext.Modelmetadata.ModelType);        }        private static bool IsJSonRequest(ControllerContext controllerContext) { var contentType = controllerContext.HttpContext.Request.ContentType; return contentType.Contains("application/json");        }    }public static class JavascriptSerializerExt {        public static object Deserialize(this JavascriptSerializer serializer, string input, Type objType) { var deserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static); // internal static method to do the work for us //Deserialize(this, input, null, this.RecursionLimit); return deserializerMethod.Invoke(serializer,     new object[] { serializer, input, objType, serializer.RecursionLimit });        }    }

并告诉MVC在您的Global.asax文件中使用它:

ModelBinders.Binders.DefaultBinder = new JsonModelBinder();

另外,此代码利用了内容类型=’application / json’,因此请确保您在jquery中进行设置,如下所示:

$.ajax({    dataType: "json",    contentType: "application/json",     type: 'POST',    url: '/Controller/Action',    data: { 'items': JSON.stringify(lineItems), 'id': documentId }});


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5440917.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存