Html.HiddenFor value property not getting set
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;
}
Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For
and take a lambda expression cannot work with weakly typed structures such as ViewData
.
Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.
For example in your case I would define a view model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
public string CRN { get; set; }
}
have my controller action populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
CRN = "foo bar"
};
return View(model);
}
and then have my strongly typed view simply use an EditorFor
helper:
@model MyViewModel
@Html.EditorFor(x => x.CRN)
which would generate me:
<input id="CRN" name="CRN" type="hidden" value="foo bar" />
in the resulting HTML.