MVC3 RedirectToAction in a post method and ViewBag suppression
Asked Answered
K

3

12

i'm currently working a list of data that i need to display in a view that represent a list and show for each item the corresponding action that can be executed, like edit them or delete them. For the edition there is no problem concedering that it's a particular view. My problem is when i want to delete an item, i have two choices in the post method.

 //Call directly the list 
 [HttpPost]
 [Authorize]
 public ActionResult Delete(int itemId)
 {
     // logic to delete an item
     ViewBag.Error = ""; // The result of the execution
     return List(); 
 }

The thing with this solution is that the url is no longer the same as the first one : .../List, it's .../Delete now, i don't find this solution great, the other solution is to redirect to the action, now the url is good, but the error message in the viewBag is no longer visible, Do you guys have some better idea.

Kingsize answered 12/4, 2012 at 13:11 Comment(0)
K
36

You can use TempData to persist information across one request and it was meant for this exact use case. Rather than use the ViewBag use TempData["Error"] = ""; instead. Then, on the receiving end you would have a snippet like the following:

[HttpGet]
public ActionResult List() {
    ViewBag.Error = TempData["Error"];
    // ...
    return View();
}

See ASP.NET TempData persists between requests and When to use ViewBag, ViewData, or TempData in ASP.Net MVC 3.

Krill answered 12/4, 2012 at 13:17 Comment(3)
Nice suggestion to set ViewBag.Error = TempData["Error"] in the controller, so that the view need not be concerned about this detail.Mediative
Yeah, I used to have it in the view itself, but then I had a lot of logic in the view dealing with which variable to look at. I use the controller to grab all the information necessary and pass it to the view.Krill
Thanks a lot Joshua for the answer, it works fine, and thanks for the reading resources too.Kingsize
M
13

If you are doing a redirect, try using TempData instead of ViewBag. TempData is a dictionary that preserves keys/values in the user's session until the next page request. In your controller:

TempData["Error"] = "A message goes here";

In your List view that you are redirecting to:

@TempData["Error"]

Or if you are not using razor:

<%= TempData["Error"] %>
Mediative answered 12/4, 2012 at 13:16 Comment(0)
S
1

Using ViewBag to POST ActionResult:

ActionResult SubmitUser()
{
    ViewBag.Msg =TempData["Msg"];

    return view();
}

[HtttpPost]
ActionResult SubmitUser()
{
    TempData["Msg"] ="Submitted Successfully"];

    return view();
}
Scofield answered 17/5, 2016 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.