0

I have a HttpPost method which I call a submit to database add transcation. If success, I set my viewbag.result = "successfully added"

var response =  UpdateDatabase(command);
if (response.success)
  viewbag.result = "successfully added";

RedirectToActoin("SubmitApplication");

In the view,

if (!string.IsNullOrEmpty(@ViewBag.result))
{
    <p> @ViewBag.result</p>
}

I placed a breakpoint and the viewbag.result is null.

I am not sure why the viewbag.result is null. Any help is appreciated. Thanks.

user1250264
  • 897
  • 1
  • 21
  • 54

1 Answers1

2

You should use TempData["Result"] so that your data can be used after your redirect.

As MSDN states for TempData:

Represents a set of data that persists only from one request to the next.

Also, see more information about usage here:

viewbag-viewdata-and-tempdata

Sample usage:

TempData["Results"] = "successfully added";

And in your SubmitApplication method:

var message = (string)TempData["Results"];

Always check for nulls etc which I have not done in this example.

Community
  • 1
  • 1
Ric
  • 12,855
  • 3
  • 30
  • 36
  • 1
    It's better to use `TempData["Results"] as string` rather than `(string)TempData["Results"]`. The latter will raise an exception if the `TempData` value can't be casted to a string, but the former will merely set the variable to null. You should remove as many possibilities for an exception to be raise from a view as possible, since views aren't compiled until runtime. Even then, `TempData` is dynamic, so it's never evaluated until runtime. – Chris Pratt Feb 08 '16 at 14:20
  • @ChrisPratt - agreed! – Ric Feb 08 '16 at 14:21
  • Can't use TempData["Results"] because of the project. Is there anyway without turning on the session state? – user1250264 Feb 08 '16 at 15:02
  • Yes, you could try `return RedirctToAction("SubmitApplication", new {result = "successfully added"});` see here for examples: http://stackoverflow.com/questions/1257482/redirecttoaction-with-parameter – Ric Feb 08 '16 at 15:15