Saxman
Saxman

Reputation: 5089

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.

Upvotes: 6

Views: 2360

Answers (3)

SAVJunior
SAVJunior

Reputation: 21

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.

Upvotes: 2

Jake Hoffner
Jake Hoffner

Reputation: 1037

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.

Upvotes: 16

Saxman
Saxman

Reputation: 5089

My bad, seems like the problem is in the HTML, where I have the view rendered from multiple partial views, and some of the ID for the input are the same (I hide the edit view and rendered the main view using jQuery), somehow this textbox picks up the value from the view that was hidden!!! :)

Thanks all for looking.

Upvotes: 0

Related Questions