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;
  }
}

私が抱えている問題は、私のcurstom 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 に答える