简体   繁体   English

添加LabelFor所需

[英]Add required to LabelFor

I'm having the following code: 我有以下代码:

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })

And I'm looking for a way to add the html attribute required to it, so a user can't submit without having the field filld. 而且我正在寻找一种方法来添加required的html属性,因此用户无法在没有填充字段的情况下提交。 But now sure how to do? 但现在肯定该怎么办? I know the easies way is to add required But don't know how, i tryed with @html "reguired" Without any luck. 我知道简单的方法是添加required但不知道如何,我@html "reguired"使用@html "reguired"没有任何运气。

EDIT: Answere = required = "" 编辑:Answere = required =“”

You can add RequiredAttribute to your model property: 您可以将RequiredAttribute添加到模型属性:

[Required(ErrorMessage = "Title is required")]
public string Title { get;set; }

And add ValidationMessageFor to your cshtml: 并将ValidationMessageFor添加到您的cshtml:

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Model)

Then add model validation to controller method via . 然后将模型验证添加到控制器方法via It's the standard pipeline for asp.net mvc. 它是asp.net mvc的标准管道。

You also can implement your own HtmlHepler to add required attribute to your html code. 您还可以实现自己的HtmlHepler ,为html代码添加必需的属性。

You will need this for client validation 您将需要此进行客户端验证

"~/Scripts/jquery.js"
, "~/Scripts/jquery.validate.js"
,"~/Scripts/jquery.validate.unobtrusive.js"

whereas for only server side on Controller or necessary even if some disables javascript 而对于仅控制器上的服务器端或必要即使有些禁用javascript

if (ModelState.IsValid)

As above using annotation 如上所述使用注释

[Required(ErrorMessage = "Title is required")]
public string Title { get;set; }

Using Fluent API 使用Fluent API

    public class ClassNameConfiguration : EntityTypeConfiguration<ClassName>
    {
        public ClassNameConfiguration()
        {
            Property(x => x.Title).IsRequired();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM