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
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With