c# - How do I transfer ViewModel data between POST requests in ASP.NET MVC? -
i have viewmodel so:
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"); } }
then have 2 controller methods uses model:
public actionresult create() { var model = new producteditmodel(); return view(model); } [httppost] public actionresult create(producteditmodel model) { if (modelstate.isvalid) { // convert model actual entity var product = mapper.map(model, new product()); database.save(product); return view("success"); } else { return view(model); // fails } }
the first time user goes create
view, presented list of categories. however, if fail validation, view sent them, except time categories
property null. understandable because modelbinder
not persist categories
if wasn't in post request. question is, what's best way of keeping categories
persisted? can this:
[httppost] public actionresult create(producteditmodel model) { if (modelstate.isvalid) { // convert model 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); // fails } }
but ugly solution. how else can persist it? can't use hidden field because it's collection.
i typically implement lists (for drop downs) readonly property. when view gets value property self contained on needs return values.
public selectlist categories { { var categories = database.getcategories(); // made-up method return new selectlist(categories, "key", "value"); } }
if necessary can grab selected item (i.e. validation failed) property containing id posted , bound instance of class.
Comments
Post a Comment