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,那么您的原始扩展方法也应该有效. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 弹出窗口,如何在IE8中隐藏URL栏
- 当将单字节添加到响应中时,ASP.NET WebAPI输出的速度会降低
- asp.net-mvc – 今天在.NET中实现RESTful架构的最好方法是什
- asp.net-mvc – Facebook Real-time Updates不发布数据
- asp.net-core – ASP Core 2.0 app.UseJwtBearerAuthentica
- asp.net-mvc – 忽略viewstart在asp.net mvc razor视图?
- asp.net-mvc – 使旧会话Cookie无效 – ASP.Net标识
- asp.net-mvc-4 – HttpResponseException
- asp.net-mvc-4 – 如何在MVC 4中从tempdata获取对象
- asp.net-mvc – jwt令牌多租户
推荐文章
站长推荐
- 在ASP.NET上构建维基百科(学习练习).如何清理不受
- asp.net-mvc-3 – 在MVC 3.0中重写Html.BeginFor
- asp.net-mvc – 后退按钮不会导致回发到MVC中的控
- asp.net – Page_Load中的Response.Redirect
- asp.net-mvc – 在VS 2015中添加视图上下文菜单非
- asp.net – IIS 7中的会话超时
- 执行迁移EF core 2.0时出错,将Identity id从stri
- asp.net – web.config和machine.config之间的区
- 比较自托管:WCF与HttpListener
- 如何限制文件夹访问在asp.net
热点阅读