Html.EditorFor () does not comply with data annotations

I have a model with the following property:

[Required]
[HiddenInput(DisplayValue = false)]
public override int Id { get; set;}

Now I understand that html helpers must respect these data annotation attributes when rendering properties. However when i do

@Html.EditorFor(m => m.Id) 

the following html is created:

<input class="text-box single-line" id="Id" name="Id" type="number" value="2">

I expect the field to be hidden, but it is not. I found another helper that respects annotation attributes:

@Html.Editor("Id")

The created html sets the field to hidden, as it should be:

<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="2">

As far as I can tell, both helpers are from the System.Web.Mvc.Html namespace, the implementations of both of them belong to the System.Web.Mvc assembly, version 5.2.3.0.

I would like to use the @ Html.EditorFor () method, but I also need data annotations.

All ideas are welcome.

+4
1

@JakubJankowski . @Html.EditorFor() .

+2

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


All Articles