简体   繁体   中英

ASP.NET MVC5 Access ViewBag from layout?

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?

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

Edit: Updated W/ code:

//layout.cshtml
@ViewBag.username

Yields this error:

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")

An easy way is to set a ViewBag property from your view, which will then be available in your Layout file

Index.cshtml

@{
   ViewBag.Container = false;
}

_Layout.cshtml

@{
   var container = ViewBag.Container != null && !ViewBag.Container ? "" : "container";
}

<div class="@container">
   ...
</div>

Consider an Action in AppController controller which returns Index.cshtml view :

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

In my Index.cshtml view I can directly call @ViewBag.Title to get the content what I set in the action before.

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

You can even pass complex data like list and access those in view with Razor's model/Model.

I hope I helped you with this answer.

只需在您的家庭控制器中使用视图包,您也可以在布局页面上访问它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM