Asp.net mvc 4 将字符串绑定到类型

Asp.net mvc 4 将字符串绑定到类型,asp.net-mvc-4,model-binding,Asp.net Mvc 4,Model Binding,我有一个模型,类似于: 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 =&g

我有一个模型,类似于:

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>
}
...
我的观点是:

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>
}
...
。。。
@使用(Html.BeginForm()){
  • @Html.LabelFor(m=>m.PropA)
    @Html.TextBoxFor(m=>m.PropA)
  • @Html.LabelFor(m=>m.PropB)
    @Html.TextBoxFor(m=>m.PropB)
  • @LabelFor(m=>m.DataType)
    @Html.TextBoxFor(m=>m.DataType)
  • } ...
    使用默认模型绑定,可以正确设置字符串属性,但即使提供了有效的类型字符串表示形式(例如“System.String”或“System.Boolean”),类型属性也会以NULL结束


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

    根据Ant p的评论,我实现了一个从DefaultModelBinder继承的模型绑定器,并重写了BindProperty()

    有关详细信息,请参阅


    谢谢蚂蚁p

    为什么不重写默认的模型绑定器并包含对
    base.CreateModel
    的调用?重写CreateModel()并没有带来任何效果,但我能够为我想要的行为重写BindProperty()。