Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to action and need to pass data

People also ask

What is the use of redirect to action?

The RedirectToAction() Method This method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts just like as Response.

How do you pass an object from one action to another action in MVC?

You can use TempData to pass the object. This worked well, Thanks Eranga. One potential pitfall is that the object can be disposed before it gets used in the view if you have a overridden definition for Dispose in your controller(something VS tends to add in with its auto generated CRUD code).

Which is used to send data from one action to another?

Pass (send) data from one Action method to another Action method in ASP.Net MVC.


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.


Never been a fan of TempData either and additionally I didnt want to pass the success flag in the URL as I didnt want to see

App/Settings?saveSuccess=true

in the URL bar of the browser.

My solution uses a temporary cookie:

[HttpPost]
public ActionResult Settings(SettingsViewModel view)
{
    if (ModelState.IsValid)
    {
        //save
        Response.SetCookie(new HttpCookie("SettingsSaveSuccess", ""));
        return RedirectToAction("Settings");
    }
    else
    {
        return View(view);
    }     
}

and in the corresponding Get action check for the presence of this Cookie and delete it:

[HttpGet]
public ActionResult Settings()
{
    var view = new SettingsViewModel();
    //fetch from db and do your mapping
    bool saveSuccess = false;
    if (Request.Cookies["SettingsSaveSuccess"] != null)
    {
        Response.SetCookie(new HttpCookie("SettingsSaveSuccess", "") { Expires = DateTime.Now.AddDays(-1) });
        saveSuccess = true;
    }
    view.SaveSuccess = saveSuccess;
    return View(view);
}

nb this can be a fairly slipperly slope if you start to pass anything more complex than a boolean flag