Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

validation - ASP.NET MVC 5 and HTML 5 form attributes according to the W3C specs

As for as I know it seems like Microsoft are using jQuery validation attributes as default for form input attributes.

Is it possible to configure my application so if I add the Required attribute and render my form using @Html.EditorFor(x => Model) the form will be rendered using required attributes instead of data-val-required? Or am I forced to write my own EditorTemplates for all standard types?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...