Why mvc Html.HiddenFor does not render my field?

浪尽此生 提交于 2019-11-27 14:42:44

问题


I'm trying to do this simple thing

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

the model is

[HiddenInput(DisplayValue=true)]
public int Id { get; set; }

but i always get this rendered

<input type="hidden" value="0" name="UserInfo.Id" id="UserInfo_Id">

i've check and the id is NOT 0.. ?!

need some explanation here...

Edit

The problem seem's to be the post thing mentionned below. This is working

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

Thanks to Manaf


回答1:


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




回答2:


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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/3606087/why-mvc-html-hiddenfor-does-not-render-my-field

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