我想创建一种模式:
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;
}
}