ViewBag在Extension Class中返回null

dla*_*is6 7 asp.net-mvc-3

我想在我的_Layout中使用我的ViewBag,因为我的所有视图都有类似的数据.所以我在这做什么:

在我看来:

ViewBag.MetaKeywords = Model.MetaKeywords
Run Code Online (Sandbox Code Playgroud)

我在HtmlHelper上绑定了一个扩展类

public static string MetaKeywords(this HtmlHelper helper)
{
    return helper.ViewContext.Controller.ViewBag.MetaKeyWords;
}
Run Code Online (Sandbox Code Playgroud)

在我的_Layout中:

@Html.MetaKeywords()
Run Code Online (Sandbox Code Playgroud)

问题是我的扩展方法返回null.为什么我使用扩展方法而不是@ViewBag.MetaKeyWords?因为其他一些函数都有逻辑,我们希望在自己之间共享它.

谢谢您的帮助.

nem*_*esv 5

当使用剃刀ViewBag/ViewData这是在视图设置属性可以被访问helper.ViewData,而不是helper.ViewContext. ...:

 public static string MetaKeywords(this HtmlHelper helper)
 {
     return (string) helper.ViewData["MetaKeyWords"];
 }
Run Code Online (Sandbox Code Playgroud)

注意:ViewBag它只是ViewData字典周围的动态包装器.

或者,如果您ViewBag.MetaKeywords = Model.MetaKeywords在Controller中执行此操作,则原始扩展方法也应该起作用.