http://home.beisencorp.com/space.php?uid=210&do=blog&id=957
Asp.net Mvc Controller接收可控的数组或字典类型的实现方法:
方法一,(最复杂的方法)
扩展ModelBinder 完全自定义一种参数的解析方法。
/// <summary> /// 模式绑定数组接收器 eg:,接收字符数组:参数标记如 [ModelBinder(typeof(ArrayBind<string>))]string[] arrayValue /// </summary> /// <typeparam name="T"></typeparam> public class ArrayBind<T> : IModelBinder { private _T GetValue<_T>(ModelBindingContext bindingContext, string key) { ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(key); bindingContext.ModelState.SetModelValue(key, valueResult); return (_T)valueResult.ConvertTo(typeof(_T)); } #region IModelBinder 成员 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { Dictionary<int, T> list = new Dictionary<int, T>(); string[] allKey = controllerContext.HttpContext.Request.Form.AllKeys; foreach (string key in allKey) { if (!key.StartsWith(bindingContext.ModelName, StringComparison.CurrentCultureIgnoreCase)) { continue; } string[] _key = key.Split('.'); if (_key.Length != 2) { continue; } int me = 0; if (int.TryParse(_key[1], out me)) { list.Add(me, GetValue<T>(bindingContext, key)); } } var sort = from k in list orderby k.Key ascending select k; return sort.Select<KeyValuePair<int, T>, T>(C => C.Value).ToArray(); } #endregion } |
然后在Controller的action方法参数中进行标记,如:
[HttpPost] public ActionResult Edit([Bind(Prefix = "LevelDescription")][ModelBinder(typeof(ArrayBind<string>))]string[] levelOrder) { return Json(1); } |
方法二,url参数解析法
http://www.domain.com/post?levelOrder=1&levelOrder=2&levelOrder=3&levelOrder=4&levelOrder=5
方法三,
Js异步提交数据,
var _lev = {}; _lev["lev[0].Status"] = "5"; //这里必须从零开始 名字必须一样 _lev["lev[1].Status"] = "6";
$.post("Edit", _lev , function(json) { if (json == "1") { alert(''成功)} }, "json"); |
action方法,如:
[HttpPost] public ActionResult Edit(Level[] lev) { return Json(lev); } |
如果在action中欲接收一Dictionary 类型值,则变得更加方便,
$("tr[name = 'LeelArea']").each(function(index) { _lev["levelOrder1[" + index + "].key"] = index; //这里必须从零开始 名字必须一样 _lev["levelOrder1[" + index + "].value"] = $(this).find("textarea").val(); }); if ($(this).valid()) { $.post("Edit", _lev , function(json) { Alert(json); }, "json"); }
|
action方法,如:
[HttpPost] public ActionResult Edit(Dictionary<int,string> levelOrder) { return Json(1); }
|
参考老外的:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
//js
//List<User>
public class user
}