The ASP.NET MVC team made our lives easier when they created the Html editor extension method Html.EditoFor(); you just pass the model property and it creates the right editor, filling it with the property’s value…but not always!
Let’s consider that we have the conventional route definition:
and this simple action method:
and this form view:
If you have noticed, in the action method “MyAction” I didn’t make use of the passed “id” parameter; I know this is a rare case, but maybe for a rare business scenario you want to return a very similar model rather than the requested one. In our case we will return the model with the id = 3 no matter what, just for the sake of the argument.
Now if you call for the request “http://localhost:2085/MyController/MyAction” everything works as expected, and you will have the following view result:
But if you call for the request “http://localhost:2085/MyController/MyAction/5”, the result will be:
As you have noticed, the Html.EditorFor ignored the value of the property “id” in the model, and instead used the RouteData value of the key “id” passed through the URL.
Most likely this is by design; I can’t think of how a bug in the code could produce this. But according to how I see things, this can be really confusing; I should be expecting the value of the property I passed instead of the routedata value.
What do YOU think?