在MVC razor视图中添加“required”类的最佳做法是什么?

时间:2017-12-20 19:17:06

标签: asp.net-mvc razor data-annotations

我试图通过使用数据注释在HTML文本框中添加required类,但我不能。我的理解是,如果使用数据注释,MVC应该处理这个问题。我不需要在注释之上添加required。如果我错了,这是一个好习惯吗?

查看:

@Html.LabelFor(model => model.FirstName)
@Html.TextBoxFor(model => model.FirstName, new { @class = "first-name",  placeholder = "Required" })

型号:

[Display(Name = "First Name")]
[Required(ErrorMessage = "Please provide a First Name")]
[MaxLength(40)]
public string FirstName { get; set; }

Chrome DevTools中的HTML:

enter image description here

如果我在视图中添加required = "required",那么我会看到预期结果,如下所示:

@Html.LabelFor(model => model.FirstName)
@Html.TextBoxFor(model => model.FirstName, new { @class = "first-name", placeholder = "Required", required = "required" })

输出:

enter image description here

0 个答案:

没有答案