Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom HTML attributes in MVC3 Model
    text
    copied!<p>I want to create a Model:</p> <pre><code>public class TestModel { Microdata(Data = "data-test=this is a test!")] public bool Test { get; set; } } </code></pre> <p>Then in the view:</p> <pre><code>@Html.DisplayForModel() </code></pre> <p>The result i'm looking for is something like this: </p> <pre><code>&lt;label&gt;Test:&lt;/label&gt; &lt;input type="checkbox" data-test="this is a test!" /&gt; </code></pre> <p>I've already created a custom attribute class, but this didn't produce anything. </p> <pre><code>[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&lt;Attribute&gt; attributes, Type containerType, Func&lt;object&gt; modelAccessor, Type modelType, string propertyName) { var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); var additionalValues = attributes.OfType&lt;HtmlPropertiesAttribute&gt;().FirstOrDefault(); if (additionalValues != null) { metadata.AdditionalValues.Add("HtmlAttributes", additionalValues); } return metadata; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload