Reputation: 13772
I am trying to work out whether I am misunderstanding something about ASP.NET MVC or whether I have found some sort of bug in ASP.NET MVC Beta 3. I am having a problem with a PartialView picking up the wrong model when using HTML Helper extensions
My controller code looks like this:
public ActionResult EditGeneral(MapGeneralViewModel vm)
{
var query = MapGeneralViewModel.ToModel(vm, svcMaps);
return PartialView("General", MapGeneralViewModel.FromModel(query));
}
In the case of this being an insert, the property vm.Id starts out as -1 and after the call to MapGeneralViewModel.ToModel it has been persisted the database and query.Id has a proper value.
The call to MapSettingsViewModel.FromModel returns a new viewmodel and I have checked that the Id property correct contains the newly created id value.
The relevant bits of the view look like:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AdminWebRole.Models.Map.MapGeneralViewModel>" %>
<%: Model.Id %>
<%= Html.Hidden("IdTest", Model.Id) %>
<%= Html.HiddenFor(model => model.Id) %>
If I put a breakpoint in the view, Model.Id is correctly set to the right value.
The actual output of the controller (when Model.Id == 70) looks like this:
70
<input id="IdTest" name="IdTest" type="hidden" value="-1" />
<input id="Id" name="Id" type="hidden" value="-1" />
So the value output without using the HTML helpers is correct, but the values output by the helpers somehow is picking up the viewmodel that was passed into the controller !
I have no idea how this is happening. I have tried various things:
Am I confused over how this is supposed to work or have I hit a beta bug ? If it makes any difference, this is running inside my local Azure runtime on a Win7 64 bit machine.
Upvotes: 2
Views: 1178
Reputation: 29
I have just come across a similar issue in a partial view that I use for displaying the items in an order.
I was using the following to render a hidden input.
@Html.Hidden("salesorderlineid", orderLine.SalesOrderLineID)
This works fine until I delete an item, when the ID of the wrong (deleted) item is used. I double-checked the model, this was correct and rendered correctly in other usages on the same view.
I coded the hidden input directly as html and it works fine - looks like an MVC3 bug perhaps?
<input type="hidden" name="salesorderlineid" value="@orderLine.SalesOrderLineID"/>
Upvotes: 1
Reputation: 24754
There is no way that MVC is just picking up a variable that you haven't explicitly passed to your view or have hanging around in Session or TempData.
Since you're setting that Id to -1 I'm start there for problems.
The other possibility is that -1 is hanging around in your ModelState someplace. The HTML helpers look to ModelState first before deciding to use any values you pass in.
Upvotes: 1