Why mvc Html.HiddenFor does not render my field?

孤人 提交于 2019-11-28 23:21:56
Manaf Abu.Rous

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 :)

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);
}

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")

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!