3

如何为具有多态对象集合的复杂模型编写自定义模型绑定器?

我有下一个模型结构:

public class CustomAttributeValueViewModel
{
    public int? CustomAttributeValueId { get; set; }
    public int CustomAttributeId { get; set; }
    public int EntityId { get; set; }
    public CustomisableTypes EntityType { get; set; }
    public string AttributeClassType { get; set; }
}

public class CustomStringViewModel : CustomAttributeValueViewModel
{
    public string Value { get; set; }
}

public class CustomIntegerViewModel : CustomAttributeValueViewModel
{
    public int Value { get; set; }
}

如果我想将 CustomAttributeValueViewModel 绑定到它的一些继承者,我使用这样的自定义模型绑定器:

public class CustomAttributeValueModelBinder : DefaultModelBinder
{
    protected override object CreateModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext,
        Type modelType)
    {
        if (modelType == typeof(CustomAttributeValueViewModel))
        {
            var attributeClassType = (string)bindingContext.ValueProvider
                .GetValue("AttributeClassType")
                .ConvertTo(typeof(string));

            Assembly assembly = typeof(CustomAttributeValueViewModel).Assembly;
            Type instantiationType = assembly.GetType(attributeClassType, true);

            var obj = Activator.CreateInstance(instantiationType);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
            bindingContext.ModelMetadata.Model = obj;
            return obj;
        }

        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

它工作得很好。但是现在我想将这些模型绑定为另一个模型的集合项。例如:

public class SomeEntity
{
    // different properties here

    public IList<CustomAttributeValueViewModel> CustomAttributes { get; set; }
}

我怎样才能做到这一点?

编辑:

我想绑定从客户那里收到的发布数据。为了更清楚,这是我的 POST HTTP 请求的示例:

POST someUrl HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Type: application/json; charset=utf-8
Content-Length: 115

{
  "ProductName": "Product Name",
  "CustomAttributeValues": [
    {
      "CustomAttributeId": "1",
      "Value": "123",
      "AttributeClassType": "namespace.CustomStringViewModel"
    }
  ]
}

我在我的行动中收到了这些数据:

public void Save([ModelBinder(typeof(SomeBinder))] SomeEntity model)
{
    // some logic
}

我想写这样的活页夹来收集继承者。

4

1 回答 1

4

您需要包含完整路径AttributeClassType

var valueProviderResult = bindingContext.ValueProvider
                            .GetValue(bindingContext.ModelName + ".AttributeClassType");

请看一下这个工作的 Github 示例

于 2014-11-03T10:40:28.827 回答