Add to LabelFor

I have 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 to it required, so the user cannot send without filling the filld field. But now sure how to do it? I know the easy way is to add requiredBut I don't know how, I tried using @html "reguired"No luck.

EDIT: Answere = required = ""

+4
source share
2 answers

You can add RequiredAttribute to the model property:

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

And add ValidationMessageFor to your cshtml:

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

Then add model validation to the controller method via . This is the standard pipeline for asp.net mvc.

HtmlHepler, html-.

+2

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

, javascript

if (ModelState.IsValid)

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

Fluent API

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

Source: https://habr.com/ru/post/1620500/


All Articles