ASP.NET MVC5从布局访问ViewBag? [英] ASP.NET MVC5 Access ViewBag from layout?

查看:178
本文介绍了ASP.NET MVC5从布局访问ViewBag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将动态数据从控制器传递到我的视图和布局.我目前正在使用ViewBag将数据从Controller传递到视图,该视图工作正常.我无法从布局中访问ViewBag.有没有办法做到这一点?

I'm currently trying to pass dynamic data from my controller to my view AND layout. I'm currently using the ViewBag to pass data from the Controller to the view which works fine. I'm not able to access the ViewBag from within the layout. Is there a way to do this?

我正在使用ASP.NET W/MVC5(C#).

I'm using ASP.NET W/ MVC5 (C#).

更新后的W/代码:

//layout.cshtml
@ViewBag.username

产生此错误:

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'ViewBag' does not exist in the current context

推荐答案

我建议您使用布局所使用的操作方法,该方法可以传递所需的数据.例如

I would suggest that you have an action method, which the layout uses, that passes the data you need. For example

public class ControllerName : Controller
{
    public ActionMethod GetData()
    {
       return Content("Some data"); // Of whatever you need to return.
    }
}

然后在布局和可以调用的视图中

then in the layout and the view you can call

@Html.Action("GetData", "ControllerName")

这篇关于ASP.NET MVC5从布局访问ViewBag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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