首页 > 其他 > 详细

原来自定义模型绑定器还可以这么玩

时间:2014-11-10 11:18:31      阅读:179      评论:0      收藏:0      [点我收藏+]

我有个功能,需要绑定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视图模型的时候,可以在控制器的方法里自动绑定,实现了我想要的效果。

原来自定义模型绑定器还可以这么玩

原文:http://www.cnblogs.com/subendong/p/4086627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!