繁体   English   中英

用于具有多态对象集合的复杂模型的定制模型绑定器

[英]Custom model binder for complex model with collection of polymorphic objects

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

我有模型的下一个结构:

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
}

我想写这样的活页夹,以获取继承的集合。

您需要包含AttributeClassType完整路径,

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM