栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将JSON数据发布到ASP.NET MVC

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将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 }});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号