1

在我的自定义 ASP.NET MVC ModelBinder 中,我必须绑定 MyType 类型的对象:

public class MyType
{
  public TypeEnum Type { get; set; }
  public string Tag { get; set; } // To be set when Type == TypeEnum.Type123
}

在上面的伪代码中,您可以看到我希望仅在“Type”为 Type123 时设置属性“Tag”。

我的自定义 ModelBinder 像这样:

public class CustomModelBinder : DefaultModelBinder
{
  protected override void BindProperty(ControllerContext cc, ModelBindingContext mbc, PropertyDescriptor pd)
  {
    var propInfo = bindingContext.Model.GetType().GetProperty(propertyDescriptor.Name);
    switch (propertyDescriptor.Name)
    {
      case "Type": // ....
        var type = (TypeEnum)controllerContext.HttpContext.Request.Form["Type"].ToString();
        propInfo.SetValue(bindingContext.Model, name, null);
        break;
      case "Tag": // ...
        if (bindingContext.Model.Type == TypeEnum.Type123) { // Fill 'Tag' }
        break;
  }
}

我遇到的问题是,在我的自定义 ModelBinder 中,我无法控制 ASP.NET MVC 绑定属性的顺序。

您知道如何指定 ASP.NET MV 填充属性的顺序吗?

4

3 回答 3

1

您可以尝试覆盖该BindModel方法:

public class MyTypeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = (MyType)base.BindModel(controllerContext, bindingContext);
        if (model.Type != TypeEnum.Type123)
        {
            model.Tag = null;
        }
        return model;
    }
}
于 2012-08-17T12:10:17.137 回答
0

您可以在自定义模型绑定器中尝试此操作:

    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form);
        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }

然后从 formCollection 中提取您需要的内容。祝你好运。

于 2012-08-17T12:10:02.070 回答
0

您可以重写该GetModelProperties方法并促进该System.ComponentModel.PropertyDescriptorCollection.Sort(string[])方法对属性进行重新排序(请注意,此方法有几个重载)。在您的情况下,这应该会给您带来预期的结果:

protected override PropertyDescriptorCollection GetModelProperties(
    ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return base.GetModelProperties(controllerContext, bindingContext)
            .Sort(new[] { "Type", "Tag" });
    }
于 2015-10-23T07:58:40.917 回答