Redirect to action and need to pass data

EDIT: Sorry, didn’t originally see your note about not wanting to use TempData.

In a nutshell – do you want your message to reappear if the client refreshes/reloads the page they’ve been redirected to?

If you do, then use the querystring, something like:

return(RedirectToAction("Index", new { message = "hi there!" }));

and then either define

public ActionResult Index(string message) { }

or explicitly pull out Request.QueryString[“message”] and pass it to the View via ViewData in the usual way. This will also work on browsers that aren’t accepting cookies from your site.

If you DON’T want the message to display again, then ASP.NET MVC 1.0 provides the TempData collection for this exact purpose.

TempData property values are stored in session state until the next request from the same browser, after which they are cleared – so if you put something in TempData immediately before returning RedirectToAction, it’ll be available on the result of the redirect but will be cleared immediately afterwards.

Here’s a simple change to the HomeController in the ASP.NET MVC startup project:

public ActionResult Index() {
    ViewData["Message"] = "Welcome to ASP.NET MVC!";
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string submitButton) {
    TempData["message"] = "You clicked " + submitButton;
return(RedirectToAction("Index"));
}

public ActionResult About() {
    return View();
}

and the corresponding view /Views/Home/Index.aspx should contain something like this:

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
  <% if (TempData["message"] != null) { %>
    <p><%= Html.Encode(TempData["message"]) %></p>
  <% } %>
  <% using (Html.BeginForm()) { %>
    <input type="submit" name="submitButton" value="Button One" />
    <input type="submit" name="submitButton" value="Button Two" />
  <% } %>
</asp:Content>

You’ll notice the TempData message is displayed immediately following a POST-REDIRECT-GET sequence, but if you refresh the page, it won’t be displayed again.

Note that this behaviour has changed in ASP.NET MVC 2 – see “Passing State between Action Methods” in this article for more information.

Leave a Comment