wudi

博客园 首页 新随笔 联系 订阅 管理

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

    }

 

然后在Controlleraction方法参数中进行标记,如:

        [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

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

 

//js

    //List<User>

          var _lev = {};
          _lev["user[0].name"] = "wudi";
          _lev["user[0].pwd"] = "pwd";
          _lev["user[1].name"] = "wudi";
          _lev["user[1].pwd"] = "pwd";
          $.post("/home/Add", _lev, function(result) {
              if (result <= 0) {
                  alert('保存记录失败!');
              }
              else {
                  c_pr_c.ID = result;
              }
          }, "json");
          //Dictionary<string,user>
          var _lev = {};
          _lev["stock[0].key"] = "MSFT"
          _lev["stock[0].value"] = "Microsoft Corporation"
          _lev["stock[1].key"]= "AAPL"
          _lev["stock[1].value"] = "Apple, Inc."
          $.post("/home/AddDic", _lev, function(result) {
              if (result <= 0) {
                  alert('保存记录失败!');
              }
              else {
                  c_pr_c.ID = result;
              }
          }, "json");

 

    public class user

    {
        public string name { get; set; }
        public string pwd { get; set; }
    }

 

 public ActionResult Add(List<user> user)
        {
            return View();
        }
        public ActionResult AddDic(IDictionary<string, string> stock)
        {
            return View();

        } 

 

 

 

posted on 2010-08-26 21:31  菜鸟吴迪  阅读(5296)  评论(1编辑  收藏  举报