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.

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Fully qualify with System.Web.Mvc.HiddenInput or add the namespace.
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.
Is there any reason why one would not use the html helper @Html.hiddenfor(_ => _.FOO) in the view?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.