2011-12-09 117 views
7

我想在我的_Layout中使用我的ViewBag,因为我所有的视图都有类似的数据。所以在这里我做什么:ViewBag在扩展类中返回null

在我看来:

ViewBag.MetaKeywords = Model.MetaKeywords 

我有绑定的的HtmlHelper

public static string MetaKeywords(this HtmlHelper helper) 
{ 
    return helper.ViewContext.Controller.ViewBag.MetaKeyWords; 
} 

在我_layout的扩展类:

@Html.MetaKeywords() 

的问题是我的扩展方法返回null。为什么我使用扩展方法而不是@ViewBag.MetaKeyWords?因为一些其他功能有逻辑,我们想在我们之间分享它。

谢谢你的帮助。

+3

您正在设置'ViewBag.MetaDescription',但您尝试访问您的帮助器中的'ViewBag.MetaKeyWords'是否是您的示例代码中的拼写错误?因为属性名称应该匹配。 – nemesv

+0

对不起,我在我的文章中发了一个错误,我修改了它,所以我的问题依然存在。 – dlanglois6

回答

5

当使用剃刀分别在视图设置ViewBag/ViewData性能可与helper.ViewData代替helper.ViewContext. ...访问:

public static string MetaKeywords(this HtmlHelper helper) 
{ 
    return (string) helper.ViewData["MetaKeyWords"]; 
} 

注:ViewBag是就在ViewData字典动态包装。

或者如果您在控制器中执行ViewBag.MetaKeywords = Model.MetaKeywords,那么您的原始扩展方法也应该起作用。

+0

这正是我需要的!我不记得在哪里,但有些事情指出我使用helper.ViewContext来访问ViewBag,这是不正确的,所以谢谢! – Campbeln