76

I thought this would be a quick search on google but maybe I'm missing something. Is there a way, using Data Annotations, to set a ViewModel property to create a HiddenInput when the markup get rendered?

The only annotations I've found were to hide the property from the view entirely, I still want the property rendered but as a hidden input.

Justin Soliz
  • 2,781
  • 3
  • 25
  • 33

1 Answers1

135

This property:

[System.Web.Mvc.HiddenInput(DisplayValue = false)]
public int Id { get; set; }

will be rendered as i.e.

<input id="Id" name="Id" type="hidden" value="21" />

when using Html.EditorForModel() or Html.EditorFor(m => m.Id)

miensol
  • 39,733
  • 7
  • 116
  • 112
  • 7
    Fully qualify with System.Web.Mvc.HiddenInput or add the namespace. – Jason Mar 02 '11 at 19:37
  • Thanks, it worked well except Id property. I haven't known why, of course there was completely no validation attribute for Id property in my code. – Tien Do Aug 20 '12 at 14:16
  • 2
    Is there any reason why one would not use the html helper `@Html.hiddenfor(_ => _.FOO) ` in the view? –  Jan 28 '15 at 07:57
  • 3
    @gerdi you may want to leave the views (the .cshtml) alone and control the output by the model attributes only. Or you may wish to use @Html.EditorForModel() in which case you're not writing Razor code, and so you'd need the attribute. – VictorySaber Apr 13 '15 at 14:41