简体   繁体   中英

Static member being removed in HttpPost

In an ASP.NetCore MVC Controller I am adding a new object (Restaurant) to the static list _restaurantData with the HttpPost Create method below, and then redirecting to the "Details" page of the new Restaurant. While debugging, I can verify that the new restaurant is added to _restaurantData with all the correct properites and the correct id is passed into the RedirectToAction method. Once 'Details' is actually called though, the new Restaurant object has been removed from _restaurantData and so 'model' is null. How could the new restaurant possibly be removed from the list between "Create"'s return statement and the beginning of "Details"? And how could I 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 is code to add restaurant to list.

public void Add(Restaurant newRestaurant)
    {
        newRestaurant.Id = _restaurants.Max(r => r.Id) + 1;
        _restaurants.Add(newRestaurant);
    }

When you redirect, the state of the page (and its underlying controller class), is lost, including static variables. What you need to do is save after you have added the new instance:

_restaurantData.Add(restaurant);
_restaurantData.SaveChanges(); // Assuming DbContext

Then, when your page loads on the Details page, the database will have the model saved and will successfully retrieve it.

If _restaurantData is not a DbContext , you need it to have some way to save the data between page loads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM