如何在 _ViewStart.cshtml 上设置 ViewBag 属性? [英] How do I set ViewBag properties on _ViewStart.cshtml?
问题描述
我有一个特定的 ViewBag 属性,我想在 ViewStart 级别设置它.理想情况下,如有必要,我希望能够在页面基础上覆盖该属性.这可能吗?如果是这样,我如何访问 ViewStart 页面中的 ViewBag 属性?
I have a specific ViewBag property that I would like to set at the ViewStart level. Ideally, I would like to be able to override that property on a page basis, if necessary. Is this possible? If so, how do I access the ViewBag property within a ViewStart page?
推荐答案
有两种方法:
使用
PageData
属性(它更适用于 ASP.NET 网页,很少在 MVC 中使用)
Use the
PageData
property (it's something more applicable to ASP.NET WebPages and seldom used in MVC)
设置:
@{
PageData["message"] = "Hello";
}
检索
Retrieve
<h2>@PageData["message"]</h2>
尝试找到视图实例(代码有点脏,但它确实可以让您直接访问ViewBag
/ViewData
Try to find the view instance (the code is a bit dirty, but it does give you access directly to ViewBag
/ViewData
设置:
@{
var c = this.ChildPage;
while (c != null) {
var vp = c as WebViewPage;
if (vp != null) {
vp.ViewBag.Message = "Hello1";
break;
}
c = c.ChildPage;
}
}
检索:照常
Retrieve: as per usual
<h2>@ViewBag.Message</h2>
这篇关于如何在 _ViewStart.cshtml 上设置 ViewBag 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!