Html.HiddenFor value property not getting set

前端 未结 6 1745
借酒劲吻你
借酒劲吻你 2020-12-09 15:26

I could have used

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

but, I get,

6条回答
  •  暖寄归人
    2020-12-09 15:53

    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:

    
    

    in the resulting HTML.

提交回复
热议问题