Yuriy Mayorov
Yuriy Mayorov

Reputation: 971

asp mvc 4. Get current model in controller

In my action I need to delete some rows from database. But if exception is thrown, I need to return View with current model:

[HttpGet]
    public ActionResult Delete(int id)
    {
        try
        {
            mDataMgr.DeleteUnit(id);
        }
        catch (DataManagerException ex)
        {
            if (ex.Error == DataManagerError.UnitHasMaps)
            {
                ModelState.AddModelError(String.Empty, "Unit has maps");
                UnitRegionsViewModel regionsVM = new UnitRegionsViewModel()
                {
                    Regions = mDataMgr.UnitRegions(id),
                    UnitId = id
                };

                return View("View", regionsVM);
            }
        }

        return RedirectToAction("List");
    }

I have to reload my current Model from database. Is there any ways to get current Model in my action?

Upvotes: 1

Views: 5232

Answers (2)

Sleek
Sleek

Reputation: 221

Alternatively, you could fetch that model from the database and send it back? Since you have the Id that should be something you might do. Or a better way is let the delete Action accept the complete model. That way you can just return it if delete fails without fetching from the DB? Or, your delete method in your repository should send back a complete model if delete fails? All can be done.

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

There is no such thing as a "current model". Web pages are "stateless". Once a page is rendered, all information about that page is gone, including its model. One would normally post the model back to the controller if they want to get that information.

You could certainly serialize your model to hidden fields in the page, then accept that model as a parameter to your Delete method. However, if any of that information is sensitive, this is not something you should do.

Upvotes: 2

Related Questions