I have a situation in which there’s an HTTP GET parameter with name “Date” and that makes impossible for me to create a TextBox which name is “Date” and setting the value I want on it.
In my View, if I write:
@Html.TextBox("Date", "99/99/9999")
The TextBox will be rendered not with the value 99/99/9999 but with the value that is coming from the request, let’s say: 02/07/2012. The same happens if I use EditorFor passing a value from the view-model (that I actively set to a value different from 02/07/2012)
I cant override the request data no matter what.
What should I do?
EDIT
As Darin Dimitrov wisely explained, whenever you want to modify a value coming from the request in order to display it in the View, you have to remove it from ModelState.
This is specially useful when dealing with DateTime in GET requests. ASP.NET MVC Model binding forces the date to be in the format MM/dd/yyyy in GET requests. But when you want to display it to the user, you may want to reformat it to dd/MM/yyyy possibly using the DisplayFormatAttribute. However that is not possible unless you remove the date from ModelState first.
Remove it from the ModelState in your POST controller action:
Obviously you don’t won’t to work with weakly typed helpers:
You want to work with strongly typed models and editor templates:
And in your POST controller action you will set the required date:
I have explicitly used string as the Date property here which is probably wrong, I was just stumped with the validity of the 99/99/9999 string as a date. But obviously the same applies for dates as well.
The reason for this is that HTML helpers first look at the ModelState when binding their values and after that in the model. So even if you modify the value in the model, if you have a different value in the ModelState (which often happens in POST actions) it will be the value from the ModelState that will get used. This is by design.