代码之家  ›  专栏  ›  技术社区  ›  Mitch Rosenburg

向DefaultModelBinder MVC2添加多个前缀

  •  1
  • Mitch Rosenburg  · 技术社区  · 16 年前

    <%= Html.TextBox("User.FirstName") %>
    <%= Html.TextBox("User.LastName") %>
    

    在post上绑定到此方法

    public ActionResult Index(UserInputModel input) {}
    

    public class UserInputModel {
        public string FirstName {get; set;}
        public string LastName {get; set;}
    }
    

    惯例是使用类名sans“InputModel”,但我不想每次都用BindAttribute指定它,即:

    public ActionResult Index([Bind(Prefix="User")]UserInputModel input) {}
    

    2 回复  |  直到 16 年前
        1
  •  2
  •   Nathan Anderson    15 年前

    这个 ModelName ModelBindingContext 对象传递给 BindModel

     public class PrefixedModelBinder : DefaultModelBinder
     {
         public string ModelPrefix
         {
             get;
             set;
         }
    
         public PrefixedModelBinder(string modelPrefix)
         {
             ModelPrefix = modelPrefix;
         }
    
         public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
         {
             bindingContext.ModelName = ModelPrefix;
             return base.BindModel(controllerContext, bindingContext);
         }
     }
    

    在你的邮箱里注册 Application_Start 像这样:

    ModelBinders.Binders.Add(typeof(MyType), new PrefixedModelBinder("Content"));
    

    Bind

        2
  •  1
  •   Derek Greer    16 年前

    BindAttribute可以在类级别使用,以避免对UserInputModel参数的每个实例重复它。

    仅从表单中删除前缀或在视图模型上使用BindAttribute是最简单的选择,但另一种选择是为UserInputModel类型注册自定义模型绑定器,并显式查找所需的前缀。

    推荐文章