我正在嘗試編輯記錄。我有默認路由。
當我點擊提交按鈕,我在UpdateModel行上得到一個異常:
'MyProject.Mvc.Models.Product'類型的模型無法更新。
在頁面上,ProductId字段的驗證提示該值無效:
值'9'無效。 9是我嘗試編輯的記錄的ID。 什麼可能是錯的?如何使用MVC2 RC2更新
public ActionResult Edit(int id)
{
Product product = productRepository.GetProduct(id);
return View(new ProductFormViewModel(product));
}
[HttpPost]
public ActionResult Edit(int id, FormCollection productFormViewModel)
{
Product product = productRepository.GetProduct(id);
try
{
// TODO: Add update logic here
UpdateModel(product, "Product");
productRepository.Save();
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View(new ProductFormViewModel(product));
}
}
如果我更改更新模型線:
UpdateModel(product);
則不會拋出異常,並且數據沒有在數據庫中更新。
[編輯]
我使用實體框架
namespace MyProject.Mvc.Models
{
[MetadataType(typeof(ProductMetaData))]
public partial class Product
{
public Product()
{
// Initialize Product
this.CreateDate = System.DateTime.Now;
}
}
public class ProductMetaData
{
[Required(ErrorMessage = "Product name is required")]
[StringLength(50, ErrorMessage = "Product name must be under 50 characters")]
public object ProductName { get; set; }
[Required(ErrorMessage = "Description is required")]
public object Description { get; set; }
}
public class ProductFormViewModel
{
public Product Product { get; private set; }
public ProductFormViewModel()
{
Product = new Product();
}
public ProductFormViewModel(Product product)
{
Product = product;
}
}
}
我使用NerdDinner作爲指南。 – Picflight 2010-03-04 07:21:09
問題在於編輯視圖,<%@ Page Title =「」Language =「C#」MasterPageFile =「〜/ Views/Shared/Site.Master」Inherits =「System.Web.Mvc.ViewPage「%>如果我傳入視圖模型ProductFormViewModel它不會更新,但如果我將它更改爲<%@ Page Title =」「Language =」C#「MasterPageFile =」〜/ Views/Shared/Site.Master 「Inherits =」System.Web.Mvc.ViewPage 「%>它更新。 –
Picflight
2010-03-11 16:23:10