Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag return null in Extension Class

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.

like image 582
dlanglois6 Avatar asked Dec 09 '11 18:12

dlanglois6


People also ask

Does ViewBag expire?

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.

How does ViewBag work internally?

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

How do I pass ViewBag from controller view?

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.

How does ViewData work?

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.


1 Answers

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.

like image 54
nemesv Avatar answered Oct 20 '22 05:10

nemesv