ASP.NET MVC 5和HTML 5根据W3C规范形成属性

Mar*_*cus 4 validation asp.net-mvc asp.net-mvc-5

至于我知道,似乎Microsoft正在使用jQuery验证属性作为表单输入属性的默认值.

是否可以配置我的应用程序,所以如果我添加Required属性并使用@Html.EditorFor(x => Model)表单呈现我的表单将使用required属性而不是data-val-required?还是我被迫EditorTemplates为所有标准类型编写自己的?

Dar*_*rov 10

如果要替换data-*ASP.NET MVC使用的标准验证属性,首先应在web.config中禁用不显眼的客户端验证:

<add key="ClientValidationEnabled" value="false" />
Run Code Online (Sandbox Code Playgroud)

这将阻止html助手在输入字段上发出它们.

然后,您可以为标准类型编写自定义编辑器模板.例如,对于字符串,它将是~/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)
Run Code Online (Sandbox Code Playgroud)

这就是它.现在,每当你执行Html.EditorFor(x => x.Foo)where Foo字符串属性时,它将生成以下标记:

<input class="text-box single-line" id="Foo" name="Foo" required="required" type="text" value="" />
Run Code Online (Sandbox Code Playgroud)

还值得一提的是,如果您不想禁用不显眼的客户端验证和data-*整个应用程序的属性,但仅针对单个表单,您可以这样做:

@using (Html.BeginForm())
{
    this.ViewContext.ClientValidationEnabled = false;
    @Html.EditorFor(x => x.Foo)
}
Run Code Online (Sandbox Code Playgroud)