May
Html.EditorFor, Model Property vs RouteData Value
Filed Under (Misc) by Emad Alashi on 13-05-2012
Tagged Under : asp.net mvc, html.editorfor, route, routedata
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:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
and this simple action method:
public ActionResult MyAction(int? id)
{
var result = new Person() { Id = 3, Name = "My Name" };
return View(result);
}
and this form view:
@using (Html.BeginForm())
{
@Html.EditorFor( m => m.Id )
<br />
@Html.EditorFor( m => m.Name )
<br />
<input type="submit" value="Submit" />
}
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?



