sách gpt4 ăn đã đi

Chất kết dính mô hình tùy chỉnh cho các mô hình phức tạp với bộ sưu tập các đối tượng đa hình

In lại Tác giả: Walker 123 更新时间:2023-11-30 22:02:38 27 4
mua khóa gpt4 giày nike

如何为包含多态对象集合的复杂模型编写自定义模型绑定(bind)程序?

我有下一个模型结构:

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 绑定(bind)到它的某些继承者,我会使用这样的自定义模型绑定(bind)器:

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

效果很好。但现在我想将此类模型绑定(bind)为另一个模型的集合项。例如:

public class SomeEntity
{
// different properties here

public IList CustomAttributes { get; set; }
}

我该怎么做?

已编辑:

我想绑定(bind)从客户那里收到的发布数据。为了更清楚起见,这是我的 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
}

我想写这样的 Binder 来获取继承者的集合。

câu trả lời hay nhất

您需要包含 AttributeClassType 的完整路径,

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

请看这个working Github sample

关于c# - 具有多态对象集合的复杂模型的自定义模型绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26709747/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress