Html.HiddenFor value property not getting set

Sekhar picture Sekhar · Jul 27, 2011 · Viewed 108.2k times · Source

I could have used

@Html.HiddenFor(x=> ViewData["crn"])

but, I get,

<input id="ViewData_crn_" name="ViewData[crn]" type="hidden" value="500" />

To somehow circumvent that issue(id=ViewData_crn_ and name=ViewData[crn]), I tried doing the following, but the "value" attribute isn't getting set.

@Html.HiddenFor(x => x.CRN, new { @value="1"})
@Html.HiddenFor(x => x.CRN, new { @Value="1"})

generates

<input id="CRN" name="CRN" type="hidden" value="" />
<input Value="500" id="CRN" name="CRN" type="hidden" value="" />

Am I doing anything wrong?? Thanks

Answer

Gudradain picture Gudradain · Nov 27, 2013

The following will work in MVC 4

@Html.HiddenFor(x => x.CRN, new { @Value = "1" });

@Value property is case sensitive. You need a capital 'V' on @Value.

Here is my model

public int CRN { get; set; }

Here is what is output in html when you look in the browser

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

Here is my method

[HttpPost]
public ActionResult MyMethod(MyViewModel viewModel)
{
  int crn = viewModel.CRN;
}