I'm trying to create a ASP.NET MVC 2 webapp using the Northwind database following the NerdDinner tutorial, but now I keep getting the following error when trying to EDIT a product:
Value of member 'SupplierID' of an object of type 'Supplier' changed. A member defining the identity of the object cannot be changed. Consider adding a new object with new identity and deleting the existing one instead.
This happens only when I change the Category and/or Suppliers (both are DropDownLists), the other fields (checkbox and textbox) are ok.
I also can't CREATE a new product since the Model.IsValid
always return false for some reason (no exceptions).
What am I doing wrong?
ProductController.cs
public ActionResult Edit(int id) {
Product productToEdit = productsRepository.Get(id);
return View(new ProductViewModel(productToEdit));
}
[HttpPost]
public ActionResult Edit(int id, FormCollection formValues) {
Product productToEdit = productsRepository.Get(id);
if (TryUpdateModel(productToEdit, "Product")) {
productsRepository.Save();
return RedirectToAction("Details", new { id = productToEdit.开发者_运维知识库ProductID });
}
return View(productToEdit);
}
ProductViewModel.cs
public class ProductViewModel {
public Product Product { get; private set; }
public SelectList Suppliers { get; private set; }
public SelectList Categories { get; private set; }
public ProductViewModel(Product product) {
this.Product = product;
this.Suppliers = new SelectList(new SuppliersRepository()
.GetAllSuppliers()
.Select(s => new SelectListItem {
Text = s.CompanyName,
Value = s.SupplierID.ToString()
}), "Value", "Text");
this.Categories = new SelectList(new CategoriesRepository()
.GetAllCategories()
.Select(c => new SelectListItem {
Text = c.CategoryName,
Value = c.CategoryID.ToString()
}), "Value", "Text");
}
}
ProductForm.ascx
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.SupplierID) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.Product.Supplier.SupplierID, Model.Suppliers) %>
</div>
Of course, these codes are only excerpts of each Controller and Views. The ProductViewModel
is the complete code. I omited the ProductRepository
class.
put a break point in ur controller action method and read the modelstate object. inspect each key to check if there is an error. the description of error will help. before that try
<div class="editor-field">
<%= Html.DropDownListFor(model => model.SupplierID, Model.Suppliers) %>
</div>
this is what i do when editing foreign key value through listbox in L2S. not sure if u r using EF.
精彩评论