Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

The TempData controller property can be used to achieve this kind of functionality. Its main drawback in my opinion is that it uses the session storage in to store its contents. This means that you'll have extra work getting it to function on a web farm, or that you need to turn on sessions in the first place.

The good thing about TempData is that is exactly does what you want. Its a string based dictionary and you can put anything in it and by default get it out only once. So before calling RedirectToAction() you set your message. On the next request you check for messages and display them. By retrieving the messages they are automatically deleted at the end of the request.

As an alternative you could use cookies for transporting the message between the two requests. Essentially you could either roll your own solution, or implement a custom ITempDataProvider which transports the contents of TempData via cookies. Note that you need to properly secure cookies. MachineKey.Protect() can help you if you are rolling your own.

I was facing the same problem you did and created a solution for it called FlashMessage. Perhaps this could save you some work. It's available on NuGet as well. Usage is simple: you simply queue a message before you call RedirectToAction() as follows:

if(result == "nocommonfields")
{
    FlashMessage.Warning("Your error message");
    return RedirectToAction("AdminUsers", "Admin");
}

In your view you include the following statement to render any previously queued messages:

@Html.RenderFlashMessages()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top