最后我想通了!谢谢大家的建议!我终于找到了最好的解决方案,就是通过Http
Post传递JSON并使用自定义ModelBinder将JSON转换为Dictionary。我在解决方案中所做的一件事是创建了一个从Dictionary继承的JsonDictionary对象,以便可以将自定义ModelBinder附加到JsonDictionary类型,并且如果以后将Dictionary作为ActionResult参数使用时,将来也不会引起任何冲突。与JSON的目的不同。
这是最终的ActionResult方法:
public ActionResult AddItems([Bind(Include="values")] JsonDictionary values){ // do something}
和jQuery“ $ .post”调用:
$.post("/Controller/AddItems",{ values: Sys.Serialization.JavascriptSerializer.serialize( { id: 200, "name": "Chris" } )},function(data) { },"json");
然后需要注册JsonDictionaryModelBinder,我将其添加到Global.asax.cs中的Application_Start方法中:
protected void Application_Start(){ ModelBinders.Binders.Add(typeof(JsonDictionary), new JsonDictionaryModelBinder());}
最后,这是我创建的JsonDictionaryModelBinder对象和JsonDictionary对象:
public class JsonDictionary : Dictionary<string, object>{ public JsonDictionary() { } public void Add(JsonDictionary jsonDictionary) { if (jsonDictionary != null) { foreach (var k in jsonDictionary.Keys) { this.Add(k, jsonDictionary[k]); } } }}public class JsonDictionaryModelBinder : IModelBinder{ #region IModelBinder Members public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.Model == null) { bindingContext.Model = new JsonDictionary(); } var model = bindingContext.Model as JsonDictionary; if (bindingContext.ModelType == typeof(JsonDictionary)) { // Deserialize each form/querystring item specified in the "includeProperties" // parameter that was passed to the "UpdateModel" method call // Check/Add Form Collection this.addRequestValues( model, controllerContext.RequestContext.HttpContext.Request.Form, controllerContext, bindingContext); // Check/Add QueryString Collection this.addRequestValues( model, controllerContext.RequestContext.HttpContext.Request.QueryString, controllerContext, bindingContext); } return model; } #endregion private void addRequestValues(JsonDictionary model, NamevalueCollection namevalueCollection, ControllerContext controllerContext, ModelBindingContext bindingContext) { foreach (string key in namevalueCollection.Keys) { if (bindingContext.PropertyFilter(key)) { var jsonText = namevalueCollection[key]; var newModel = deserializeJson(jsonText); // Add the new JSON key/value pairs to the Model model.Add(newModel); } } } private JsonDictionary deserializeJson(string json) { // Must Reference "System.Web.Extensions" in order to use the JavascriptSerializer var serializer = new System.Web.script.Serialization.JavascriptSerializer(); return serializer.Deserialize<JsonDictionary>(json); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)