I've inherited an MVC project and I'm having some trouble as I am very new to MVC and web development in general.
The project contains a Controller Action method which generates a view. This method can either be called when the user accesses the view directly via the UI, or to regenerate the view after the user has clicked a button on the view to perform an action. If the view is regenerated after an action is performed, a verification message needs to appear on the page.
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 view, we load the value stored in TempData into a variable, and then test to see if the variable contains anything. If the variable is not null, I am attempting to 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 UI rather than Redirect from MyAction(), my log indicates that actionResult is null, however, when it is called via Redirect 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 in MyAction().
Anyone see a smoking gun here?