Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mvc Html.HiddenFor does not render my field?

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

like image 594
mateo Avatar asked Aug 31 '10 04:08

mateo


People also ask

What is HTML HiddenFor in MVC?

The Html. HiddenFor<TModel, TProperty> extension method is a strongly typed extension method generates a hidden input element for the model property specified using a lambda expression. Visit docs.microsoft.com to know all the overloads of HiddenFor() method. Example: HiddenFor() in Razor View.

How does HTML HiddenFor work?

HiddenFor<TModel,TProperty>(HtmlHelper<TModel>, Expression<Func<TModel,TProperty>>, IDictionary<String,Object>) Returns an HTML hidden input element for each property in the object that is represented by the specified expression, using the specified HTML attributes.


1 Answers

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

like image 194
Manaf Abu.Rous Avatar answered Sep 22 '22 12:09

Manaf Abu.Rous