I've inherited an MVC project where the page should display a message indicating success if an invoked Action completes properly. I'm having some trouble as I am very new to MVC and web development in general.
In the cshtml file, we have the following in MainWindow.cshtml, which only renders the table in the conditional if a string named "SavedMessage" exists in the ViewBag and is not null or empty:
@{ string actionResult = ViewBag.SavedMessage; }
@if (!string.IsNullOrEmpty(actionResult))
{
<tr>
<td>
@actionResult
</td>
</tr>
}
In the Action method, I'm attempting to use the TempData object to transfer the string value to the Action which generates the view:
public partial class ApproveController : Controller
{
const string IDX_ACTIONRESULT = @"ActionResult";
public ActionResult MyAction(FormCollection collection)
{
try
{
string result_success = @"Action completed successfully";
//Do stuff
TempData[IDX_ACTIONRESULT] = result_success;
return RedirectToAction("MainWindow");
}
catch (Exception e)
{
Logger.reportException(e);
throw e;
}
}
}
In the Action which generates the page, we load the value stored in TempData into a variable, and then test to see if the variable contains anything (note: this same Action is used to render the page whether the user just landed here, or they have clicked the button to execute MyAction). If the variable is not null, we load whatever it contains into the ViewBag.
Create View Action:
public partial class ApproveController : Controller
{
public ActionResult MainWindow()
{
//Do Stuff
var actionResult = TempData[IDX_ACTIONRESULT];
if (actionResult != null)
{
Log.info("Action Result Message: " + actionResult);
ViewBag.SavedMessage = actionResult;
}
else
Log.info("Action Result Message is NULL");
return View();
}
}
Possible lead: When the MainWindow() method is called through a means other than Redirect from MyAction(), my log indicates that actionResult is null, however, when it is called via Redirection from MyAction(), actionResult is an empty string. This leads me to believe that MyAction() is populating TempData with something but I can't see why it doesn't contain the string I'm assigning. Anyone see a smoking gun here?

CreateViewActionin the controller besides the one you posted here? Also, you should usestring.IsNullOrWhiteSpaceinstead ofsavedMessage != null && savedMessage.Length > 0.