asp.net-mvc 如何将“必需”属性添加到 mvc razor 视图模型文本输入编辑器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23071795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add "required" attribute to mvc razor viewmodel text input editor
提问by Eugene Goldberg
I have the following MVC 5 Razor HTML helper:
我有以下 MVC 5 Razor HTML 助手:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", @placeholder = "short name"})
I need this field to be required (i.e. have a red outline when user navigates out without putting a value inn). In a WebForms HTML 5 I could just say <input type="text" required />to have this effect.
What is the proper syntax to accomplish this in a Razor syntax?
我需要这个字段是必需的(即当用户导航出去而不放置值旅馆时有一个红色轮廓)。在 WebForms HTML 5 中,我只能说<input type="text" required />有这种效果。在 Razor 语法中完成此操作的正确语法是什么?
回答by Erik Philips
You can use the requiredhtml attribute if you want:
required如果需要,您可以使用html 属性:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", placeholder = "short name", required="required"})
or you can use the RequiredAttributeclass in .Net. With jQuery the RequiredAttributecan Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.
或者您可以使用.Net 中的RequiredAttribute类。使用 jQuery,RequiredAttribute可以在前端和服务器端进行验证。如果你想走 MVC 路线,我建议阅读Data annotations MVC3 Required attribute。
OR
或者
You can get really advanced:
你可以变得非常先进:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
@Html.TextBoxFor(m => m.ShortName, attributes)
}
or if you need it for multiple editor templates:
或者如果您需要它用于多个编辑器模板:
public static class ViewPageExtensions
{
public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
instance.Html.GetUnobtrusiveValidationAttributes(
instance.ViewData.TemplateInfo.HtmlFieldPrefix));
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
}
}
then in your templates:
然后在您的模板中:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = this.GetAttributes();
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
@Html.TextBoxFor(m => m.ShortName, attributes)
}
Update 1 (for Tomaswho is unfamilar with ViewData).
更新 1(适用于不熟悉 ViewData 的Tomas)。
What's the difference between ViewData and ViewBag?
Excerpt:
摘抄:
So basically it (ViewBag) replaces magic strings:
ViewData["Foo"]with magic properties:
ViewBag.Foo
所以基本上它(ViewBag)替换了魔法字符串:
ViewData["Foo"]具有魔法属性:
ViewBag.Foo
回答by Floremin
On your model class decorate that property with [Required]attribute. I.e.:
在您的模型类上用[Required]属性装饰该属性。IE:
[Required]
public string ShortName {get; set;}
回答by bvpb
A newer way to do this in .NET Core is with TagHelpers.
在 .NET Core 中执行此操作的一种新方法是使用TagHelpers.
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
Building on these examples (MaxLength, Label), you can extend the existing TagHelperto suit your needs.
基于这些示例(MaxLength、Label),您可以扩展现有示例TagHelper以满足您的需求。
RequiredTagHelper.cs
必需的TagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;
namespace ProjectName.TagHelpers
{
[HtmlTargetElement("input", Attributes = "asp-for")]
public class RequiredTagHelper : TagHelper
{
public override int Order
{
get { return int.MaxValue; }
}
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (context.AllAttributes["required"] == null)
{
var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
if (isRequired)
{
var requiredAttribute = new TagHelperAttribute("required");
output.Attributes.Add(requiredAttribute);
}
}
}
}
}
You'll then need to add it to be used in your views:
然后,您需要添加它以在您的视图中使用:
_ViewImports.cshtml
_ViewImports.cshtml
@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"
Given the following model:
给定以下模型:
Foo.cs
文件
using System;
using System.ComponentModel.DataAnnotations;
namespace ProjectName.Models
{
public class Foo
{
public int Id { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
}
}
and view (snippet):
并查看(片段):
New.cshtml
新建.cshtml
<label asp-for="Name"></label>
<input asp-for="Name"/>
Will result in this HTML:
将导致此 HTML:
<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>
I hope this is helpful to anyone with same question but using .NET Core.
我希望这对任何有相同问题但使用 .NET Core 的人有所帮助。
回答by estellezg
I needed the "required" HTML5 atribute, so I did something like this:
我需要“必需的”HTML5 属性,所以我做了这样的事情:
<%: Html.TextBoxFor(model => model.Name, new { @required = true })%>
回答by Matas Vaitkevicius
@Erik's answer didn't fly for me.
@Erik 的回答并不适合我。
Following did:
以下做了:
@Html.TextBoxFor(m => m.ShortName, new { data_val_required = "You need me" })
plus doing this manually under field I had to add error message container
加上在字段下手动执行此操作,我不得不添加错误消息容器
@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
Hope this saves you some time.
希望这可以为您节省一些时间。

