2013-11-25 33 views
2

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

我使用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 
+1

你能附加一些你试过的代码片段吗? –

+0

你应该可以做到这一点。发布你的代码会有帮助。 – erdinger

+1

你的'Views'目录中是否有Web.config?一些信息在这里:http://stackoverflow.com/questions/15550899/the-name-viewbag-does-not-exist-in-the-current-context和http://stackoverflow.com/questions/4960148/the- name-viewbag-does-exist-in-the-current-context – erdinger

回答

7

我建议你有一个动作的方法,其布局中使用,即通过你所需要的数据。例如

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

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

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

简单而甜美! – RayLoveless

0

考虑的AppController控制器的动作返回Index.cshtml观点:

public class AppController: Controller 
{ 
    public IActionResult Index() 
    { 
     ViewBag.Title = "Home Page"; 
     return View(); 
    } 
} 

在我的指数。 cshtml视图我可以直接调用@ ViewBag.Title来获取我在之前的动作中设置的内容。

<head> 
    <meta charset="UTF-8" /> 
    <title>@ViewBag.Title | Example.com</title> 
    <link href="css/site.css" rel="stylesheet" type="text/css" /> 
</head> 

你甚至可以通过复杂的数据,如列表和访问这些鉴于与Razor的模型/模型。

我希望我帮你解答了这个问题。