asp.net-mvcredirecttoaction

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?


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.