在Helper中使用TempData出现错误: 当前上下文中不存在'TempData'的名称。

8
我想在我的帮助程序中访问TempData以便于生成一个类似Ruby中的flash消息。
我遇到了一个运行时错误。
The name 'TempData' does not exist in the current context

我的Flash.cshtml代码如下:
@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>
}

在布局中,我有:
<section id="main">
    @Flash.Show() 
    <div id="flash" style="display: none"></div>
    @RenderBody()
</section>
4个回答

13

TempData属于ControllerBase类,这是控制器的基类,它不能被共享视图访问,因为没有控制器与之相关联。

一个可能的解决方法是将控制器传递给您的Helper方法,或通过HtmlHelper访问它。

@helper SomeHelper(HtmlHelper helper)
{
  helper.ViewContext.Controller.TempData
}

我能够使用这个答案来完成相同的事情,尽管不是在帮助程序中。https://dev59.com/_G035IYBdhLWcg3wK8wm#5582533 谢谢 - eiu165
不要把-controller-传递到-view-中。你可以设置一个过滤器,自动将TempData推送到ViewBag中,或者使用控制器基类中的OnActionExecuting、OnActionExecuted方法来填充ViewBag数据。直接从视图中访问控制器方法/字段/ foo几乎会破坏封装性。两个示例之间的区别在于链接的解决方案不在视图中使用控制器。 - Cornelius
您现在可以使用helper.ViewContext.TempData。 - Kevin Swarts

4

只需将TempData传递给您的帮助程序。

在您的布局中调用帮助程序将如下所示。

@Flash.Show(TempData)

您的Flash.cshtml辅助程序将如下所示。
@helper Show(System.Web.Mvc.TempDataDictionary tempData)
{
    // The contents are identical to the OP's code,
    // except change all instances of TempData to tempData.
}

0

0
一些人也使用TempData来帮助数据在重定向后存活。如果是这种情况,你可以通过首先将数据分配给TempData来解决问题:
TempData["myStuff"] = myData;

然后在您的新重定向操作内:

ViewBag["myBaggedStuff"] = TempData["myStuff"];

然后在你的共享视图中使用ViewBag。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接