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

  • 相关阅读:
    Linux磁盘分区、格式化和挂载
    通过Fiddler监控Java应用发送请求及相应数据
    使用Apache Commons IO组件读取大文件
    export default 和 export 的使用方式
    vue+webpack4 脚手架搭建
    async/await中reject的问题
    NodeJS 开发博客(五) 使用express脚手架
    常考JS题笔记
    让你弄懂 call、apply、bind的应用和区别
    JS闭包解析
  • 原文地址:https://www.cnblogs.com/subendong/p/4086627.html
Copyright © 2011-2022 走看看