自定义模型绑定

 public class GC_ModelBindcs : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            List<Model> model = (List<Model>)bindingContext.Model ?? new List<Model>();
            // string str = bindingContext.ValueProvider.GetValue("arrMachine[0][status]").AttemptedValue;
            int count = 0;
            if (controllerContext.HttpContext.Request.Form.AllKeys.Length > 0)
            {
                count = (controllerContext.HttpContext.Request.Form.AllKeys.Length - 1) / 2;
            }
            for (int i = 0; i < count; i++)
            {
                Model m = new Model();
                string id_key = bindingContext.ModelName + "[" + i + "]" + "[id]";
                string status_key = bindingContext.ModelName + "[" + i + "]" + "[status]";
                m.id = int.Parse(bindingContext.ValueProvider.GetValue(id_key).AttemptedValue);
                m.status = bool.Parse(bindingContext.ValueProvider.GetValue(status_key).AttemptedValue);
                model.Add(m);
            }
            return model;
        }
    }

MVC后台:

 public ActionResult Index_Post(int groupId, [ModelBinder(typeof(GC_ModelBindcs))]List<Model> arrMachine)
        {
            
            return View();
        }

 

posted @ 2016-06-01 16:28  小小高  阅读(263)  评论(0编辑  收藏  举报