代码之家  ›  专栏  ›  技术社区  ›  brunosp86 diceguyd30

ViewModels和创建/编辑操作出错

  •  1
  • brunosp86 diceguyd30  · 技术社区  · 15 年前

    我正在尝试按照Nerddinner教程使用Northwind数据库创建一个ASP.NET MVC 2 Web应用程序,但现在我在尝试编辑产品时一直遇到以下错误:

    类型为“supplier”的对象的成员“supplierID”的值已更改。 无法更改定义对象标识的成员。 考虑添加具有新标识的新对象,并删除现有对象。

    只有当我更改类别和/或供应商(两者都是下拉列表)时,其他字段(复选框和文本框)才正常。

    我也无法创建新产品,因为 Model.IsValid 总是出于某种原因返回false(没有异常)。

    我做错什么了?

    产品控制器.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);
        }
    

    产品视图模型.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");
        }
    }
    

    产品窗体.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 班级。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Muhammad Adeel Zahid    15 年前

    在UR控制器操作方法中放置一个断点并读取ModelState对象。检查每把钥匙是否有错误。对错误的描述将有所帮助。在尝试之前

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

    这是我在L2S中通过列表框编辑外键值时所做的。不确定U R是否使用EF。