asp.net的MVC模型中添加元数据属性无 [英] asp.net mvc add model meta data without attributes
问题描述
在我们的asp.net mvc的形式,我们通常将属性添加到我们的,如显示名称,说明及所需要的视图模型属性。
In our asp.net mvc forms we will typically add attributes to our view model properties such as DisplayName, Description and Required.
我们会那么就叫 Html.EditorFor(型号=> model.PropertyName)。
每个属性
We'll then just call Html.EditorFor(model => model.PropertyName)
for each property.
我现在有一个情况下,我没有一个强类型的视图模型,而我可以申请这样的属性。相反,我有下面的类的列表:
I now have a situation where I don't have a strongly typed viewmodel to which I can apply such attributes. Instead I have a list of the following class:
public class AttributeValue
{
public string Name { get; set; }
public string Description { get; set; }
public bool Required { get;set; }
public object AttributeValue { get; set; }
}
我如何添加元数据手动使用存储在上面的类的信息,从而使 EditorFor
帮助和验证仍然有效?
推荐答案
您应该定制ModelMetadataProvider编写和ModelValidatorProvider类
You should write custom ModelMetadataProvider and ModelValidatorProvider classes
public class DynamicModelValidatorProvider : ModelValidatorProvider
{
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
{
// you validation logic go there
yield break;
}
}
public class DynamicModelMetadataProvider : ModelMetadataProvider
{
public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)
{
yield return new ModelMetadata(this, containerType, null, typeof (string), "Hello");
yield return new ModelMetadata(this, containerType, null, typeof (string), "World");
}
public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
{
return GetMetadataForProperties(null, containerType).SingleOrDefault(x => x.PropertyName == propertyName);
}
public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)
{
return new ModelMetadata(this, null, modelAccessor, modelType, null);
}
}
这篇关于asp.net的MVC模型中添加元数据属性无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!