MVC 2 View showing wrong model info
I'm using MVC 2 for a project and I'm having a problem with a view. In the controller I have the code:
return View(calendarDay);
If I debug this line and inspect calendarDay it tells me the calendarDay.Id property is equal to 2. In the view I have some code like this:
<%: Html.HiddenFor(model => model.Id) %>
However, when the view is shown after binding it to a calendarDay with Id property = 2 I get this on the generated HTML:
<input id="Id" name="Id" type="hidden" value="1">
The value is 1, so when I do the TryUpdateModel(calendarDay) it gets the Id property to 1 instead of 2 and when I go to the repository to get the object to delete it, it crashes because it finds the wrong one. Anyone knows what I might be d开发者_JAVA技巧oing wrong?
I suspect that you are trying to modify the POSTed value (which is 1) in your controller action to 2. This is not possible because that's how all HTML helpers work and it is by design: they will first look at the POSTed value when binding and after that in the model. So the HiddenFor
helper ignores the Id of your model and uses the one that's posted.
As a workaround you could:
<input type="hidden" name="Id" value="<%: Model.Id %>" />
As suggested by @jfar in the comments section another workaround is to clear the model state in the post action before returning the view:
MoselState.Clear();
Seems like the problem is that the view is using the id from the controller and not the one from the model. I just changed the parameter name and works fine now.
精彩评论