views:

153

answers:

1

Although I have read the documentation on Html.HiddenFor, I've not grasped what is it used for...

Could somebody explain its uses and give a short example?

Where should those helpers go in the code?

+4  A: 

Creates a hidden input on the form for the field (from your model) that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be modified seen by the user.

Consider the following ViewModel class:

public class ViewModel
{
    public string Value { get; set; }
    public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be editable seen:

<% using(Html.BeginForm() { %>
    <%= Html.HiddenFor(model.Id) %><br />
    <%= Html.TextBoxFor(model.Value) %>
<% } %>

Which results in the equivalent of the following HTML:

<form name="form1">
    <input type="hidden" name="Id">2</input>
    <input type="text" name="Value" value="Some Text" />
</form>
Justin Niessner
Where should that helper go in the code?
JPCF
<%= Html.HiddenFor(model.Id) %><br /> in his example above
Bryce Fischer
I would say "seen" by the user. Users can "modify" anything they want to, hidden or not.
Craig Stuntz
@Craig - You're right. I actually though I changed that wording but apparently not.
Justin Niessner