I’m working on an ASP.NET MVC 2 app in which the client wants to manage his products and stuff.
One requirement is that the user needs to have the possibility to make a copy of an existing product.
I have an edit view where a product can be modified. In that view i have an action link to a copy action method to which the id of the current product is passed.
public ActionResult Copy(Guid id)
{
var original = this.Repository.GetById(id);
var viewModel = this.GetNewViewModel();
if (original != null)
{
this.InvalidateCache();
viewModel = this.Mapper.Map(original);
}
viewModel.Id = Guid.NewGuid();
return this.View("Index", this.GetMasterDetailViewModel(viewModel));
}
I got some headache because I was using Html.EditorFor(m => m.Id) on the view, which in the case of a Guid creates a hidden field using the Html.Hidden(HtmlHelper, String, Object).
In the copy action I fetch the existing entity and map it to a new viewmodel(I don’t create an entity in the datastore yet so that the user can cancel the copy process). Then the same view that is used to display an existing product is used to display the copy of the product.
So basically I have two times the same viewmodel(except the id) passed to the same view and then posted back to the same URL. Here comes the problem with Html.EditorFor(m => m.Id).
For some reason in the second postback, the value of the Guid is taken from the model state, aka what you get is a cached value.
For my case this means that after the copy action is called I get the exact same HTML as if I wanted to display the original product. And then obviously if the user edits something and hits the save butten, the original is modified and not the copy.
A workaround for this is to write your own markup like this:
<input id="Selected_Id" type="hidden" value="<%=Model.Selected.Id%>" name="Selected.Id" />
Like this the value is taken from the passed viewmodel, not from the model state and everything works fine.
This behaviour is by design and I think there must be a good reason for it(but I actually don’t speak enough ASP.NET MVC to truly understand why..). For further information here’s a discussion on Stack Overflow about the issue:






0 Response to “Html.EditorFor with Guid as model results in unexpected behaviour”