Html.HiddenFor value property not getting set

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

I could have used

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

but, I get,

相关标签:
6条回答
  • 2020-12-09 15:52

    Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.

    0 讨论(0)
  • 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:

    <input id="CRN" name="CRN" type="hidden" value="foo bar" />
    

    in the resulting HTML.

    0 讨论(0)
  • 2020-12-09 15:57

    I believe there is a simpler solution. You must use Html.Hidden instead of Html.HiddenFor. Look:

    @Html.Hidden("CRN", ViewData["crn"]);
    

    This will create an INPUT tag of type="hidden", with id="CRN" and name="CRN", and the correct value inside the value attribute.

    Hope it helps!

    0 讨论(0)
  • 2020-12-09 16:02

    A simple answer is to use @Html.TextboxFor but place it in a div that is hidden with style. Example: In View:

    <div style="display:none"> @Html.TextboxFor(x=>x.CRN) </div>

    0 讨论(0)
  • 2020-12-09 16:09

    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;
    }
    
    0 讨论(0)
  • 2020-12-09 16:16

    Simple way

    @{
       Model.CRN = ViewBag.CRN;
    }
    
    @Html.HiddenFor(x => x.CRN)
    
    0 讨论(0)
提交回复
热议问题