asp.net-mvcrazorviewdatahtml.hiddenfor

Html.HiddenFor value property not getting set


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


Solution

  • 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.