I want to use my ViewBag in my _Layout, because all my views have similar data. So here what I do:
In my View:
ViewBag.MetaKeywords = Model.MetaKeywords
I have an extension class binded on the HtmlHelper
public static string MetaKeywords(this HtmlHelper helper)
{
return helper.ViewContext.Controller.ViewBag.MetaKeyWords;
}
And in my _Layout:
@Html.MetaKeywords()
The problem is my extension method returns null. Why I use an extension method instead of @ViewBag.MetaKeyWords
? Because some other functions have logic and we want to share it between ourself.
Thank you for your help.
ViewBag is a property of ControllerBase class. It's life also lies only during the current request. If redirection occurs then it's value becomes null.
In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class. Compared to ViewData, it works similarly but is known to be a bit slower and was introduced in ASP.NET MVC 3.0 (ViewData was introduced in MVC 1.0).
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.
It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary. The only limitation of ViewData is, it can transfer data from controller to view. It can not transfer in any other way and it is valid only during the current request.
When using Razor the ViewBag/ViewData
properties which were set in the View can be accessed with helper.ViewData
instead of helper.ViewContext. ...
:
public static string MetaKeywords(this HtmlHelper helper)
{
return (string) helper.ViewData["MetaKeyWords"];
}
Note: The ViewBag
is just a dynamic wrapper around the ViewData
dictionary.
Or if you do the ViewBag.MetaKeywords = Model.MetaKeywords
in the Controller then your original extension method should also work.
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