2010-10-07 21 views
1

我想創建一個ASP.NET MVC 2 webapp使用NerdDinner教程後的羅斯文數據庫,但現在我試圖編輯產品時不斷收到以下錯誤:錯誤與ViewModels和創建/編輯操作

「供應商」類型對象的成員「供應商ID」值已更改。 定義對象身份的成員無法更改。 考慮添加一個具有新身份的新對象,並刪除現有的對象。

只有當我更改類別和/或供應商(均爲DropDownLists),其他字段(複選框和文本框)都可以時纔會發生這種情況。

我也無法創建新產品,因爲Model.IsValid由於某種原因總是返回false(沒有例外)。

我在做什麼錯?

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> 

當然,這些代碼是每個控制器和視圖的僅摘錄。 ProductViewModel是完整的代碼。我省略了ProductRepository班。

+0

而不是Nerddinner,請閱讀Steve Sanderson關於MVC的書。他有一些關於爲演示文稿編寫的樣本的說法,而不是工作示例。 – awrigley 2010-10-07 18:47:52

+0

@awrigley,NerdDinner是一個工作的例子:http://www.nerddinner.com/ – 2010-10-07 18:58:59

+0

我知道。我看過視頻。我讀過這本書。我還讀過史蒂夫桑德森的書。從後來你會對MVC有一個更好的「工作」的想法。即使它有效,Nerddinner仍然是作爲演示文稿創建的,而不是作爲解決常見編程問題的工具。 – awrigley 2010-10-07 19:37:12

回答

1

在你的控制器動作方法中放一個斷點並讀取modelstate對象。檢查每個鍵檢查是否有錯誤。錯誤的描述將有所幫助。在此之前嘗試

<div class="editor-field"> 
      <%= Html.DropDownListFor(model => model.SupplierID, Model.Suppliers) %> 
     </div> 

這是我在通過L2S中的列表框編輯外鍵值時所做的。不確定是否使用EF。

+0

哦!幾乎是這樣!相反,在下拉菜單中選擇了「amodel.Product.Supplier.SupplierID」,我做了「amodel.Product.SupplierID」!非常感謝!! – BrunoSalvino 2010-10-07 19:07:43

+0

我最歡迎:) – 2010-10-07 19:09:40

相關問題