jbq jbq - 3 months ago 14
C# Question

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

Answer

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