0

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 doing wrong?

brafales
  • 570
  • 3
  • 6
  • 22

2 Answers2

1

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();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    @jfar, yes that's a very good workaround suggestion. I will edit my post to include it. – Darin Dimitrov Nov 17 '10 at 13:34
  • 1
    We should write a guide for some of these questions. I think we both answer this one a couple of times a month. ;) – John Farrell Nov 17 '10 at 13:49
  • And if you only want to clear the one key, `ModelState.Remove("Id");` – David Kolar Nov 17 '10 at 20:31
  • @jfar, it's worst than that: actually it's couple of times a day. Here's another one: http://stackoverflow.com/questions/4216832/asp-net-mvc2-update-of-a-model-for-futher-modifications-in-a-post-handler/4217854#4217854. That's hilarious. – Darin Dimitrov Nov 18 '10 at 17:47
0

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.

brafales
  • 570
  • 3
  • 6
  • 22