When using any of the Input Extension Helper Methods, like @Html.TextboxFor
, any Validation Attributes from your model are automatically generated by the Razor engine (via ClientValidationEnabled
/UnobtrusiveJavaScriptEnabled
).
For example, take the following case which works fine
Model:
<!-- language: lang-cs -->[Required]
public string QuestionOne { get; set; }
View:
<!-- language: lang-cs -->@Html.TextBoxFor(model => model.QuestionOne)
@Html.ValidationMessageFor(model => model.QuestionOne)
Generated Markup:
<!-- language: lang-html --><input type="text" id="QuestionOne" name="QuestionOne" value=""
data-val="true" data-val-required="The QuestionOne field is required." >
<span class="field-validation-valid" data-valmsg-for="QuestionOne" data-valmsg-replace="true"></span>
In this case the attributes data-val="true"
& data-val-required="The QuestionOne field is required."
are picked up by Unobtrusive validation and the form element is successfully validated.
However, for extensibility reasons, I want to be able to generate the <input>
element myself instead of using TextBoxFor
. So my view would now look like this:
<input type="textbox"
id="@Html.IdFor(m => m.QuestionTwo)"
name="@Html.NameFor(m => m.QuestionTwo)"
value="@Model.QuestionTwo"
data-val="true" data-val-required="Selection is Required" />
@Html.ValidationMessageFor(model => model.QuestionTwo)
In this case, I'm faking the validation attribute output by just re-writing data-val="true" (etc)
by hand, but this would have to be expanded to cover every single case.
Here's a running Demo in .NET Fiddle
Q: Can I build /return a list of data-val-*
attributes for a given element?