代码之家  ›  专栏  ›  技术社区  ›  Andrej Kaurin

模型内部属性的自定义模型绑定器

  •  7
  • Andrej Kaurin  · 技术社区  · 16 年前

    我的模型是这样的

    public class MyModel
    {
       string ID {get;set;}
       string Title {get;set;}
       MyOtherModel Meta {get;set;}
    }
    

    我在App start中注册了它,如下所示:

     ModelBinders.Binders[typeof(MyOtherModel)] = new MyCustomBinder();
    

    但这不起作用。关于模型绑定器,有什么好主意或好文章吗?

    2 回复  |  直到 16 年前
        1
  •  1
  •   Marijn    14 年前

    有一篇关于集合的文章稍微涉及了复杂类型映射的内容:

    Collections and a bit about complex types

    另一方面,本文可以为您提供一些有用的提示:

    http://odetocode.com/Blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx

    变通办法 要为MyModel类使用模型绑定器,这不是一个完美的解决方案,但您可以 重构 一旦您发现更好的解决方案,您就可以轻松解决此问题。:)

        2
  •  0
  •   Victor Gelmutdinov    16 年前

    实际上,如果您将MyModel类的模型放入一些编辑/创建视图,如下所示:

    <%= Html.TextBox("Meta.Prop1") %>
    

    其中Prop1是MyThermodel类的属性,

    UpdateModel(model);
    

    将文本框值填充到自定义子模型属性中。返回时,文本框值也将填充该子模型值。