Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RedirectToAction not refreshing the page as expected

What am I doing wrong with my MVC code here ? The Index view includes a form that submits to itself, what I'd like is the controller to process the submitted form and then return to the View.

What actually happens is the form is processed correctly, but the View returned is as if nothing happen (e.g. ids that have been deleted are still shown). If I manually refresh the page though, it displays correctly again. I don't think it's broswer caching related, as redirecting to the same view from a different controller works fine. How can I fix it ?

    public ViewResult Index()
    {
        return View(GetComments());
    }


    [HttpPost]
    public ActionResult Index(int[] AllIds)
    {
        if (AllIds != null)
        {
            foreach (int id in AllIds)
            {
               // do stuff
            }
        }

        return RedirectToAction("Index");
    }

Edit: When submitting the form, the breakpoint on the first method is not hit and trying to "Step Into (F11)" the return RedirectToAction("Index"); line just moves straight onto the final } instead.

like image 709
Michael Low Avatar asked Dec 17 '11 00:12

Michael Low


2 Answers

Install Fiddler or Firebug for Firefox and watch the traffic, see it it really returns a new response or a HTTP 304 from the browser(cached page). If everything checks out then you have a problem with your db persistence and or queries.

like image 151
rick schott Avatar answered Nov 09 '22 08:11

rick schott


Have you tried this? I'm wondering, depending on how you persist the data, if it's not being saved until after the server returns a response..?

public ViewResult Index()
{ // breakpoint
    var comments = GetComments(); // debug and inspect the value of this variable
    return View(comments);
}


[HttpPost]
public ActionResult Index(int[] AllIds)
{
    if (AllIds != null)
    {
        foreach (int id in AllIds)
        {
           // do stuff
        }
    }

    return RedirectToAction("Index"); // breakpoint
} 

I know some people use an IUnitOfWork in MVC that only calls SaveChanges / Commit on the ORM at the end of the request. Is it possible that the // do stuff removes items from the collection, but does not persist to the db until AFTER the GET Index() is returned?

Update

Instead of return RedirectToAction("Index"), have you tried RedirectToAction(Index())?

like image 1
danludwig Avatar answered Nov 09 '22 08:11

danludwig