Redirecting Back to List Page

Currently, our list not display the item yet. Now, we want to make the item being displayed in Index page after added to the list. Basically we could do something like this.

if (ModelState.IsValid)
{
    _entriesRepository.AddEntry(entry);

    return View("Index");
}
return View(entry);

Try to run your project.

Of course, an error occurred.

Unfortunately, by returning a view from Index page, it means we are asking for another Index page. What we need is redirecting back the Index page. Then, index page will query all of the items inside _entriesRepository collection.

.NET MVC provides us a quick way to do what we want.

[ActionName("Add"), HttpPost]
public ActionResult AddPost(Entry entry)
{
    if (ModelState.IsValid)
    {
        _entriesRepository.AddEntry(entry);

        return RedirectToAction("Index");
    }
    return View(entry);
}

This method known as Post/Redirect/Get design pattern. It is a well-known method for preventing form's duplicate submission.

For deeper understanding: https://en.wikipedia.org/wiki/Post/Redirect/Get

results matching ""

    No results matching ""