zoukankan      html  css  js  c++  java
  • 原来自定义模型绑定器还可以这么玩

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

  • 相关阅读:
    漏洞都是怎么编号的CVE/CAN/BUGTRAQ/CNCVE/CNVD/CNNVD
    数据集成之主数据管理(一)基础概念篇
    hdu 4940 Destroy Transportation system(水过)
    关于C++ const 的全面总结
    UserManageSys
    malloc函数具体解释
    Haskell 差点儿无痛苦上手指南
    机房收费系统——附加数据库
    面向对象程序设计与面向过程程序设计解析
    java的System.getProperty()方法能够获取的值
  • 原文地址:https://www.cnblogs.com/subendong/p/4086627.html
Copyright © 2011-2022 走看看