我想创建一个模型:
public class TestModel
{
Microdata(Data = "data-test=this is a test!")]
public bool Test { get; set; }
}
然后在视图中:
@Html.DisplayForModel()
我正在寻找的结果是这样的:
<label>Test:</label> <input type="checkbox" data-test="this is a test!" />
我已经创建了一个自定义属性类,但这并没有产生任何东西。
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MicrodataAttribute : Attribute
{
public string Data { get; set; }
public RouteValueDictionary GetAttributes()
{
var attributes = new RouteValueDictionary();
if (this.Data != null)
{
string[] kv = this.Data.Split(',');
attributes.Add(kv[0], kv[1]);
}
return attributes;
}
}
public class MetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var additionalValues = attributes.OfType<HtmlPropertiesAttribute>().FirstOrDefault();
if (additionalValues != null)
{
metadata.AdditionalValues.Add("HtmlAttributes", additionalValues);
}
return metadata;
}
}