在布局网页使用ViewBag [英] Using ViewBag in Layout page

查看:608
本文介绍了在布局网页使用ViewBag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 ViewBag 模型来呈现一些动态内容我的 _Layout.cshtml 文件。

I have my _Layout.cshtml file that uses the ViewBag model to render some dynamic content.

我理解 ViewBag 可在控制器内填充并在视图和/或布局页面访问。

I understand ViewBag can be populated in the controller and accessed in the view and/or layout page.

我的问题是,如果我的布局页中使用 @ ViewBag.SiteName ,我想避免才返回视图设置此变量中的每个控制器。有没有一种方法来设置在全球范围内这个变量?还是怎么回事,应该怎么这个数据传递到页面布局?

My question is, if my Layout page is using @ViewBag.SiteName, I want to avoid having to set this variable in each controller before I return the view. Is there a way to set this variable on a global level? Or how else should I pass this data to the layout page?

推荐答案

如果您在ViewBag设置任何东西 - 这种情况的布局已经呈现的后 -
你已经错过了船。

If you set anything in ViewBag - this happens after the Layout has been rendered - You've missed the boat.

正如其他人所说,你可以创建一个帮手控制器:

As others have mentioned, you can create a "helper" controller:

public class LayoutController : BaseController
{
    [ChildActionOnly]
    public ActionResult SiteName()
    {
        return new ContentResult {Content = "Site name goes here"};
    }
}

然后,在你的布局:

Then, in your layout:

@{Html.Action("SiteName", "Layout")}

这篇关于在布局网页使用ViewBag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆