标签:style blog http io color ar sp for div
我有个功能,需要绑定List<User>。我做了个测试:
试图:
@using (Html.BeginForm("save", "user")) { <div> 用户名:<input type="text" name="UserName" /><br /> 用户名:<input type="text" name="UserName" /><br /> <input type="submit" value="submit" /> </div> }
模型:
public class User { public string UserName { get; set; } }
控制器:
public ActionResult Save(List<Models.User> users) { return Content("success"); }
自定义模型绑定器:
public class UsersBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { string[] userNames = controllerContext.RequestContext.HttpContext.Request.Form.GetValues("username"); List<Models.User> users = new List<Models.User>(); Models.User user; foreach (var item in userNames) { user = new Models.User { UserName = item }; users.Add(user); } return users; } }
Global.asax.cs:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); ModelBinders.Binders.Add(typeof(List<Models.User>), new Extend.UsersBinder()); }
这样通过自定义模型绑定器,当客户端有N个User视图模型的时候,可以在控制器的方法里自动绑定,实现了我想要的效果。
标签:style blog http io color ar sp for div
原文地址:http://www.cnblogs.com/subendong/p/4086627.html