MVC2 TextBoxFor value not updating after submit?

喜欢而已 提交于 2019-11-30 12:33:42
Mathias F

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

Sander

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

Simon Ince

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.

The solution is to use either ModelState.Remove("[Mode's Property Name]") before it is assigned new value with the Controller. Or on the view page, change Html.TextBoxFor() to Html.TextBox() for the particular model property.

I got the same problem with VS 2010 and I found I hit the wall the whole day. After I thought about the whole night, I think I found the reason. The reason is the persistence. It only remembers whatever value entered on the browser. However, I think this violates the binding principle. If I am allowed to pass a model parameter to the view, the view should bind that parameter by taking whatever I pass in the model's current state.

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