Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Html.TextBoxFor rendered different value than <%: Model.value %>

This is very strange and I don't know why. I have a ViewModel that return some value for my object, when rendering it, they have different values, yet, they points to the same property:

<%: Model.myProperty %>

That returns "25", which is what I've set the property to be. But when rendered it as an textbox, it returned "0" as the value for my textbox!

<%: Html.TextBoxFor(f => f.myProperty) %>

Any idea why? The property is of decimal type. Thanks.

like image 368
Saxman Avatar asked Sep 02 '10 20:09

Saxman


People also ask

What is the difference between using HTML TextBoxFor and HTML TextBox?

Both of them provide the same HTML output, “HTML. TextBoxFor” is strongly typed while “HTML. TextBox” isn't. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.

How do I use TextBoxFor in HTML?

The HtmlHelper class includes two extension methods TextBox() and TextBoxFor<TModel, TProperty>() that renders the HTML textbox control <input type="text"> in the razor view. It is recommended to use the generic TextBoxFor<TModel, TProperty>() method, which is less error prons and performs fast.

How disable HTML TextBoxFor in MVC?

You can make the input 'read only' by using 'readonly'. This will let the data be POSTED back, but the user cannot edit the information in the traditional fashion. Keep in mind that people can use a tool like Firebug or Dragonfly to edit the data and post it back.

How do I change my razor view ID?

Just add the id property to the html-attributes. That will override the default id generated by the editorfor-helper-methode.


2 Answers

Try ModelState.Clear() before calling View or PartialView and passing in the model.

This issue was happening for me after doing a post. Its because the HTML helpers get their value from ModelState first before checking the actual model. Seems like this should be reversed IMO.

like image 173
Jake Hoffner Avatar answered Nov 19 '22 19:11

Jake Hoffner


Having the same problem, I read this post today (and it’s solved my problem) and decided to investigate more regarding it. So, here is what I found:

“ASP.NET MVC assumes that if you are rendering a View in response to an HTTP POST, and you are using the Html Helpers, then you are most likely to be redisplaying a form that has failed validation. Therefore, the Html Helpers actually check in ModelState for the value to display in a field before they look in the Model.” By: Simon J Ince

If you want read more about this, access the link bellow: http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

See you.

like image 29
SAVJunior Avatar answered Nov 19 '22 19:11

SAVJunior