Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RedirecttoAction with error message

I have a link on a grid in my AdminUsers view

grid.Column(header: "", format: (item) => (condition ? Html.ActionLink("Impersonate", "Impersonate", "Admin", new { id = item.username }, null) : Html.Label("Impersonate"), style: "webgrid-column-link"),

In the controller, I have

public ActionResult Impersonate(string id)
{
    string result = ORCA.utilities.users.setImpersonation(id);
    if(result == "nocommonfields")
        return RedirectToAction("AdminUsers", "Admin");
    else
        return RedirectToAction("terms_of_use", "Forms");
}

How can send an error message to display when I return to the AdminUsers page?

like image 496
RememberME Avatar asked Apr 11 '13 20:04

RememberME


People also ask

What is difference between redirect and RedirectToAction?

RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.

How pass multiple parameters in RedirectToAction in MVC?

Second, to pass multiple parameters that the controller method expects, create a new instance of RouteValueDictionary and set the name/value pairs to pass to the method. Finally call RedirectToAction(), specifying the method name, controller name, and route values dictionary.


1 Answers

You may use TempData

if(result == "nocommonfields")
{
    TempData["ErrorMessage"]="This is the message";
    return RedirectToAction("AdminUsers", "Admin");
}

and in your AdminUsers action, you can read it

public ActionResult AdminUsers()
{
  var errMsg=TempData["ErrorMessage"] as string;
 //check errMsg value do whatever you want now as needed
}

Remember, TempData has very short-life span. Session is the backup storage behind temp data.

Alternatively, You may also consider sending a flag in your querystring and read it in your next action method and decide what error message to show.

like image 178
Shyju Avatar answered Nov 08 '22 22:11

Shyju