in asp.netcore mvc controller adding new object (restaurant) static list _restaurantdata httppost create method below, , redirecting "details" page of new restaurant. while debugging, can verify new restaurant added _restaurantdata correct properites , correct id passed redirecttoaction method. once 'details' called though, new restaurant object has been removed _restaurantdata , 'model' null. how new restaurant possibly removed list between "create"'s return statement , beginning of "details"? , how fix this!
[httppost] public iactionresult create(restuaranteditviewmodel model) { var restaurant = new restaurant(); restaurant.name = model.name; restaurant.cuisine = model.cuisine; _restaurantdata.add(restaurant); return redirecttoaction("details", new { id = restaurant.id }); } public iactionresult details(int id) { var model = _restaurantdata.get(id); if (model == null) { return redirecttoaction("index"); } return view(model); }
here code add restaurant list.
public void add(restaurant newrestaurant) { newrestaurant.id = _restaurants.max(r => r.id) + 1; _restaurants.add(newrestaurant); }
when redirect, state of page (and underlying controller class), lost, including static variables. need save after have added new instance:
_restaurantdata.add(restaurant); _restaurantdata.savechanges(); // assuming dbcontext
then, when page loads on details page, database have model saved , retrieve it.
if _restaurantdata
not dbcontext
, need have way save data between page loads.
Comments
Post a Comment