加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – ViewBag在Extension Class中返回null

发布时间:2020-12-16 04:07:04 所属栏目:asp.Net 来源:网络整理
导读:我想在我的_Layout中使用我的ViewBag,因为我的所有视图都有类似的数据.所以我在这做什么: 在我看来: ViewBag.MetaKeywords = Model.MetaKeywords 我在HtmlHelper上有一个扩展类绑定 public static string MetaKeywords(this HtmlHelper helper){ return he
我想在我的_Layout中使用我的ViewBag,因为我的所有视图都有类似的数据.所以我在这做什么:

在我看来:

ViewBag.MetaKeywords = Model.MetaKeywords

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

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

在我的_Layout中:

@Html.MetaKeywords()

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

谢谢您的帮助.

解决方法

使用Razor时,可以使用helper.ViewData而不是helper.ViewContext访问View中设置的ViewBag / ViewData属性. …:
public static string MetaKeywords(this HtmlHelper helper)
 {
     return (string) helper.ViewData["MetaKeyWords"];
 }

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

或者,如果您在Controller中执行ViewBag.MetaKeywords = Model.MetaKeywords,那么您的原始扩展方法也应该有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读