asp.net-mvc-3 – ViewBag在Extension Class中返回null
发布时间:2020-05-24 15:23:04 所属栏目:asp.Net 来源:互联网
导读:我想在我的_Layout中使用我的ViewBag,因为我的所有视图都有类似的数据.所以我在这做什么: 在我看来: ViewBag.MetaKeywords = Model.MetaKeywords 我在HtmlHelper上有一个扩展类绑定 public static string MetaKeywords(this HtmlHelper helper){ return hel
|
我想在我的_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 – 如何为ValidateAntiForgeryToken选择一个盐值
- asp.net-mvc-4 – ASP.Net Web Api在POST上不绑定模型
- asp.net – AsyncPostBackTrigger找不到LinkButton
- asp.net-mvc – 如何在ActionFilterAttribute ASP MVC 5中为
- asp.net – System.Web.HttpException:请求超时
- asp.net-mvc – ASP.NET MVC DropDownListFor不支持SelectL
- 在ASP.net中模拟HttpSessionState进行单元测试
- asp.net-mvc-3 – “..必须从WebViewPage或WebViewPage”在
- asp.net-mvc-4 – Resharper无法解析主页中的部分视图
- asp.net – 实体框架删除子对象
