MVC2 TextBoxFor value not updating after submit?

I'd avoid ModelState.Clear() or ModelState.Remove() unless you absolutely have to. Generally if you see this behaviour it is because a) you're not following the Post-Redirect-Get pattern and should be, or b) if that isn't appropriate you should consider not using the HtmlHelper's TextBox method, as it is mainly designed to help with validation etc when following a PRG pattern.

I'm sure there are exceptions (for example a Wizard-style UI can end up a bit like this), but I'd take that as the default approach.


Default Html helper try to redisplay the data that is posted to them. They first use the value from posted data and if no posted data is available they take the data from the Model.

This is not what you want obviously, but still the most common usage: You display some data in formfields after receiving a get request. You post to an Update action. If you have errors you want to redisplay the form with the values you entered still available.

I have seen some people getting around this (I think by writing to ModelState), but my choice was always to not use the default helpers if they dont help me. Thats especially true for hidden fields: Most people get confused when they set a value to a hidden field but the value that is realy used is from the post. At least there is a question every other day about it on SO :-)

Forget the "Most people" and replace it with "Everybody".

ASP.NET MVC: Hidden field value does not get rendered using HtmlHelper.Hidden

http://blog.johnwest.com/post/ASPNET-MVC-Hidden-Form-Field-Bug.aspx

http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx?utm_medium=Twitter&utm_source=Shared

UPDATE Oh I found another one from today (You are not alone):

How to update textbox value


Do ModelState.Clear(); in your controller to prevent this happening. Check MSDN for that.