(condition ? Html.ActionL...">

RedirecttoAction with error message

I have a grid link in the 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 to send an error message to display when I return to the AdminUsers page?

+6
source share
2 answers

You can use TempData strong>

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

and in 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 that TempData has a very short lifespan. A session is a backup storage for temporary data.

Alternatively, you can also consider sending the flag in turn and reading it in the next action method and deciding which error message will be shown.

+23
source

The TempData function can be used to achieve this functionality. Its main drawback, in my opinion, is that it uses session storage to store its contents. This means that you will have to do extra work to get it to work on the web farm or you need to enable sessions first.

The good thing about TempData is that it does exactly what you want. Its dictionary is string-based, and you can put anything into it and, by default, pull it out only once. Therefore, before calling RedirectToAction() you set your message. At the next request, you check the messages and display them. Receiving messages, they are automatically deleted at the end of the request.

Alternatively, you can use cookies to transport a message between two requests. In fact, you can either minimize your own solution or implement a custom ITempDataProvider that transfers the contents of TempData via cookies. Please note that you need to protect cookies correctly. MachineKey.Protect() can help you if you ride on your own.

I ran into the same problem as you and created a solution for it called FlashMessage . Perhaps this can save you some work. It is available on NuGet . The usage is simple: you simply queue the message before calling RedirectToAction() as follows:

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

In your view, you include the following statement to display any previously delivered messages:

 @Html.RenderFlashMessages() 
+2
source

All Articles