我有一個ViewModel像這樣:如何在ASP.NET MVC中的POST請求之間傳輸ViewModel數據?
public class ProductEditModel
{
public string Name { get; set; }
public int CategoryId { get; set; }
public SelectList Categories { get; set; }
public ProductEditModel()
{
var categories = Database.GetCategories(); // made-up method
Categories = new SelectList(categories, "Key", "Value");
}
}
然後我有一個使用此模型中的兩個控制器的方法:
public ActionResult Create()
{
var model = new ProductEditModel();
return View(model);
}
[HttpPost]
public ActionResult Create(ProductEditModel model)
{
if (ModelState.IsValid)
{
// convert the model to the actual entity
var product = Mapper.Map(model, new Product());
Database.Save(product);
return View("Success");
}
else
{
return View(model); // this is where it fails
}
}
的用戶第一次進入到Create
視圖,它們都帶有一個類別列表。但是,如果它們未通過驗證,則將視圖發回給它們,但這次Categories
屬性爲空。這是可以理解的,因爲ModelBinder
不持續Categories
如果在POST請求是沒有。我的問題是,保持Categories
的最佳方式是什麼?我可以這樣做:
[HttpPost]
public ActionResult Create(ProductEditModel model)
{
if (ModelState.IsValid)
{
// convert the model to the actual entity
var product = Mapper.Map(model, new Product());
Database.Save(product);
return View("Success");
}
else
{
// manually populate Categories again if validation failed
model.Categories = new SelectList(categories, "Key", "Value");
return View(model); // this is where it fails
}
}
但這是一個醜陋的解決方案。我還能堅持嗎?我不能使用隱藏字段,因爲它是一個集合。
所以,換句話說,手動重新填充列表? – 2010-11-16 03:15:05
你是什麼意思手動? – Lorenzo 2010-11-16 03:15:42
哦,哎呀,我以爲你說'BaseController',而不是'BaseModel'。 – 2010-11-16 03:17:45