Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC5 Access ViewBag from layout?

Tags:

c#

asp.net-mvc

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
like image 889
jbq Avatar asked Nov 25 '13 22:11

jbq


People also ask

Can we pass ViewBag from view to controller?

Yes you cannot pass a Viewbag from view to controller. But you can pass them using TempData. Add this to your View. But this TempData passes the information as an object.

How do I get ViewBag data in Cshtml?

cshtml view, you can access ViewBag. TotalStudents property, as shown below. Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.


1 Answers

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")
like image 80
Jason Evans Avatar answered Sep 27 '22 17:09

Jason Evans