4

I have a model with the following property:

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

Now, it is my understanding that the html helpers are supposed to honor these data annotation attributes when rendering properties. However when I do

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

the following html is produced:

<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 have found another helper which DOES honor the annotation attributes:

@Html.Editor("Id")

The html produced by this 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 namespace System.Web.Mvc.Html, implementations of both are from the System.Web.Mvc Assembly, version 5.2.3.0.

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

All ideas welcome

Toodleey
  • 913
  • 1
  • 8
  • 22
  • 3
    Maybe it has something to do with inheritance? Maybe the helper is only looking for attributes at the base class level? Just a thought – Jakub Jankowski Nov 18 '16 at 08:25
  • @JakubJankowski That was it! Strange that some of the methods look at the base class and others does not, but it certainly fixed it. Thanks. – Toodleey Nov 18 '16 at 08:35
  • @Christos in what world is this a duplicate of the post you tagged? – Toodleey Nov 18 '16 at 08:43
  • @Toodleey I don't mark questions as duplicates for a hobby. I have read your post and it seemed to me that's a duplicate of the question I mentioned. Since I didn't see any reopen vote, in order to be fair I reopened the question by my own. – Christos Nov 18 '16 at 08:52
  • @Toodleey glad that my advice helped! I've also learnt something today – Jakub Jankowski Nov 18 '16 at 09:09
  • 1
    @JakubJankowski, Sorry to disappoint, but you did not learn anything (your guess was wrong) –  Nov 18 '16 at 11:21

1 Answers1

2

Solved by @JakubJankowski in a comment. @Html.EditorFor() does not honor data annotations on overriden properties.

Toodleey
  • 913
  • 1
  • 8
  • 22
  • Wrong - The `EditorFor()` will honor data annotations on overriden properties. The html generated by `@Html.EditorFor(m => m.Id)` will not generate `` unless there is something else you have not shown us (it generates `` –  Nov 18 '16 at 10:18