I would like to access the TempData in my helper for a flash message (like in ruby)
I get a runtime error of
The name 'TempData' does not exist in the current context
my Flash.cshtml is as follows
@helper Show()
{
var message = "test message";
var className = "info";
if (TempData["info"] != null)
{
message = TempData["info"].ToString();
className = "info";
}
else if (TempData["warning"] != null)
{
message = TempData["warning"].ToString();
className = "warning";
}
else if (TempData["error"] != null)
{
message = TempData["error"].ToString();
className = "error";
}
<script>
$(document).ready(function () {
$('#flash').html('@HttpUtility.HtmlEncode(message)');
$('#flash').toggleClass('@className');
$('#flash').slideDown('slow');
$('#flash').click(function () { $('#flash').toggle('highlight') });
});
</script>
}
in the layout i have
<section id="main">
@Flash.Show()
<div id="flash" style="display: none"></div>
@RenderBody()
</section>
Passing the data from Controller to View using TempDataGo to File then New and select “Project” option. Then create the ASP.NET web application project as depicted below. Then select “Empty” and tick “MVC” then click OK. The project is created successfully.
It uses the keyvalue for passing the data and it has a need for typecasting. TempData: TempData is a dictionary that is derived from the TempDataDictionary class. The tempData Dictionary object persists only from one request to the next. You can mark one or more keys for retention using the keep method.
TempData belongs to ControllerBase
class which is base class for controllers, it's not accessible to shared views which no controller is behind them,
One possible workaround is to pass the controller to your helper method or access it through HtmlHelper.
@helper SomeHelper(HtmlHelper helper)
{
helper.ViewContext.Controller.TempData
}
Just pass TempData to your helper.
The call to the helper in your layout will look like this.
@Flash.Show(TempData)
Your Flash.cshtml helper will look like this.
@helper Show(System.Web.Mvc.TempDataDictionary tempData)
{
// The contents are identical to the OP's code,
// except change all instances of TempData to tempData.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With