Why is my textBox to use my route data?
So, I have three lines:
<div style="background-color: lightgreen;">@Html.TextBoxFor(m => m.Id)</div> <div style="background-color: green;">@Html.DisplayTextFor(m => m.Id)</div> <div style="background-color: pink;">@Model.Id</div> I determined that the light green value is not my Model.Id, but the identifier given by my route:
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "MyFunController", action = "Index", id = UrlParameter.Optional }); I have provided some explanations here:
- http://forums.asp.net/t/1792086.aspx/1
- http://www.hanselman.com/blog/TheWeeklySourceCode38ASPNETMVCBetaObscurityModelStateIsValidIsFalseBecauseModelBinderPullsValuesFromRouteData.aspx
- http://ayende.com/blog/3683/reproducing-a-bug
But they all left me from my appetite. I'm looking for a smart way around this, I donβt want to change the names of the model properties or donβt want to change the name of the route element. If I do this, it will be a big job for me and not perfect.
I'm sure I'm not the only one with this problem?
(This is MVC 4)
Thanks!
You can remove the problematic value from the ModelState (where its Html helpers come from) in the action of the controller, which displays the view:
public ActionResult SomeAction(int id) { ModelState.Remove("Id"); MyViewModel model = ... return View(model); } Now this is the Id property of your view model, which will be used by the TextBox, and not the one that comes from the route.
Obviously, only an ugly terrible workaround. The right way is, of course, to correctly define your view models so that you don't have such name conflicts.