If you want to replace the standard data-*
validation attributes used by ASP.NET MVC you should start by disabling unobtrusive client side validation in your web.config:
<add key="ClientValidationEnabled" value="false" />
This will prevent the html helpers from emitting them on your input fields.
Then you could write custom editor templates for the standard types. For example for string that would be ~/Views/Shared/editorTemplates/String.cshtml
:
@{
var attributes = new Dictionary<string, object>();
attributes["class"] = "text-box single-line";
if (ViewData.ModelMetadata.IsRequired)
{
attributes["required"] = "required";
}
}
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, attributes)
And that's pretty much it. Now everytime you do an Html.EditorFor(x => x.Foo)
where Foo
is a string property it will generate the following markup:
<input class="text-box single-line" id="Foo" name="Foo" required="required" type="text" value="" />
It's also worth mentioning that if you don't want to disable unobtrusive client side validation and the data-*
attributes for your entire application but only for a single form you could do that:
@using (Html.BeginForm())
{
this.ViewContext.ClientValidationEnabled = false;
@Html.EditorFor(x => x.Foo)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…