user1765862
user1765862

Reputation: 14145

RedirectToAction() destroys string data

Inside my controller I have string variable

private string notificationMessage = "";

which I want to use to copy it's content to ViewBag.Message and display that content on the view.

So inside my edit action I populate it's (notificationMessage) content like this

notificationMessage = "data is succ. updated!";
return RedirectToAction();

But after redirection to Index action this string variable is empty;

How can solve this?

Upvotes: 0

Views: 128

Answers (2)

Shyju
Shyju

Reputation: 218722

It is because RedirectToAction returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action. Since HTTP is stateless, you can't simply set something in one action and get it in another(when it is another GET request).

What you can do is

1) pass a querystring to your new action and check that in the next action method and show a message according to that.

return RedirectToAction("ThankYou","Account",new {msg="success"});

and in your ThankYou action

public ActionResult ThankYou(string msg)
{
  var vm=YourSuccessViewModel();
  if(msg="success") // you may do a null checking before accessing this value
  {
    vm.Message="Saved Successfully";
  }
  return View(vm);  
}

2) Store in a temporary place like Session / TempData. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only!

TempData["UserMsg"] = "Saved Successfully";
return RedirectToAction("ThankYou","Account");

and in your ThankYou action you can read it and show to user as needed.

public ActionResult ThankYou(string msg)
{
   var msg = TempData["UserMsg"] as string; 
   //to do  : do what you want with the message and return the view.
}

Session object is the backing store for the TempData object, and it is destroyed more quickly than a regular session, i.e., immediately after the subsequent request.

Upvotes: 3

ekim boran
ekim boran

Reputation: 1819

Use TempData instead of ViewBag. It persists between requests.

Upvotes: 4

Related Questions