Why mvc Html.HiddenFor does not render my field?

后端 未结 4 897
甜味超标
甜味超标 2020-12-15 07:08

I\'m trying to do this simple thing

<%= Html.HiddenFor(model => model.Id)%>

the model is

[HiddenInput(DisplayValu         


        
相关标签:
4条回答
  • 2020-12-15 07:27

    I'm not sure if this is the case with you but the Html.HiddenFor() "do not output correct values after a post if the value is changed during the post." and this is a not a bug it was designed that way.

    Quick Fix :

    Don't use the helper, try this instead :

    <input type="hidden" value="<%= Html.AttributeEncode(model.Id) %>" id="Id" name="Id" />
    

    Always worked for me :)

    0 讨论(0)
  • 2020-12-15 07:33

    I ran into this problem as well with @Html.HiddenFor.

    @Html.Hidden("Id", Model.Id) also gave value 0, but a foreign key field, e.g., @Html.Hidden("Model_Category_ModelId", Model.Category.ModelId) did work, while it @Html.HiddenFor(m => m.Category.ModelId) did not.

    My solution was to redirect to the get action, as described in ASP NET MVC Post Redirect Get Pattern.

    0 讨论(0)
  • 2020-12-15 07:39

    To add to Manaf's correct answer--you note correctly that the problem occurs in controller actions that handle posts. I was getting the same problem in a controller action that handles a get when I explicitly pass a model to a view:

    [HttpGet]
    ActionResult SearchForSomething(SearchForm searchForm)
    {
        searchForm.MyId = SomeValueFromSession;
        return View("SearchForSomething", searchForm);
    }
    

    In the view, this line that rendered a hidden input for MyId always rendered "0":

    @Html.HiddenFor(m => m.MyId);
    

    Per Darren Oster's suggestion I changed to the following and fixed the problem:

    [HttpGet]
    ActionResult SearchForSomething(SearchForm searchForm)
    {
        searchForm.MyId = SomeValueFromSession;
        ModelState.Clear();
        return View("SearchForSomething", searchForm);
    }
    
    0 讨论(0)
  • 2020-12-15 07:41

    My comment is relegated to the last place (even I couldn't find it), so:

    In case you don't want to clear the modelstate, as Darren Oster suggested, removing the problematic key worked for me: ModelState.Remove("HiddenKey")

    0 讨论(0)
提交回复
热议问题