I have a ViewModel, for example:
public class ProductEditModel
{
public string Name { get; set; }
public int CategoryId { get; set; }
public SelectList Categories { get; set; }
public ProductEditModel()
{
var categories = Database.GetCategories();
Categories = new SelectList(categories, "Key", "Value");
}
}
Then I have two controller methods that use this model:
public ActionResult Create()
{
var model = new ProductEditModel();
return View(model);
}
[HttpPost]
public ActionResult Create(ProductEditModel model)
{
if (ModelState.IsValid)
{
var product = Mapper.Map(model, new Product());
Database.Save(product);
return View("Success");
}
else
{
return View(model);
}
}
When you first access the view, the Createuser receives a list of categories. However, if they do not confirm the validation, the view returns to them, except that the property Categoriesis null. This is understandable because it is ModelBindernot saved Categoriesif it was not in the POST request. My question is: what is the best way to save Categoriespreserved? I can do something like this:
[HttpPost]
public ActionResult Create(ProductEditModel model)
{
if (ModelState.IsValid)
{
var product = Mapper.Map(model, new Product());
Database.Save(product);
return View("Success");
}
else
{
model.Categories = new SelectList(categories, "Key", "Value");
return View(model);
}
}
But this is an ugly decision. How else can I go on with this? I cannot use a hidden field because it is a collection.