【问题标题】:Binding a String to a Type将字符串绑定到类型
【发布时间】:2013-06-18 21:24:06
【问题描述】:

我有一个模型,类似于:

public class PageModel {
  public string PropA { get; set; }
  public string PropB { get; set; }      
  public Type DataType { get; set; }

  public PageModel() {}
  ...
}

然后我的观点是这样的:

...
@using (Html.BeginForm()) {
  <li>@Html.LabelFor(m => m.PropA) <br /> @Html.TextBoxFor(m => m.PropA)</li>
  <li>@Html.LabelFor(m => m.PropB) <br /> @Html.TextBoxFor(m => m.PropB)</li>
  <li>@Html.LabelFor(m => m.DataType) <br /> @Html.TextBoxFor(m => m.DataType)</li>
  <li><input type="submit" /></li>
}
...

使用默认模型绑定,String 属性设置正确,但 Type 属性最终为 NULL,即使提供了有效的 Type 字符串表示(例如“System.String”或“System.Boolean”)。

有关如何正确绑定此 Type 属性的任何建议?特定类型的自定义模型绑定器似乎是最好的方法,但我不想重写 PropA 和 PropB 的绑定。

【问题讨论】:

  • 为什么不覆盖默认模型绑定并包含对base.CreateModel的调用?
  • 重写 CreateModel() 并没有让我到任何地方,但我能够重写 BindProperty() 以获得我想要的行为。

标签: asp.net-mvc-4 model-binding


【解决方案1】:

根据 Ant P 的评论,我实现了一个继承自 DefaultModelBinder 的模型绑定器,并覆盖了 BindProperty()

详情请见http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx#s11-custom-binding-with-only-few-properties

感谢蚂蚁P!

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多