Why is HtmlHelper.ViewBag different from HtmlHelper.ViewContext.ViewBag

I wrote an extension method for HtmlHelper, which is called from the main page, which must access the ViewBag in order to get the information specified by this page.

This is the method signature:

public static string BuildFavoritesTitle(this HtmlHelper htmlHelper) { } 

I noticed that inside the method, if I access

 htmlHelper.ViewContext.ViewBag 

I get an empty ViewBag, but if access

 htmlHelper.ViewBag 

I get the "correct" ViewBag. Correctly, I mean a ViewBag with elements added to the inner page.

I like to know what is the difference, why is there more than one ViewBag?

+4
source share
1 answer

What purpose do you set the values ​​in the view data dictionary? Is this a peculiar property to determine how to render a control?

Consider adding an additional / s option to the BuildFavoritesTitle

 public static string BuildFavoritesTitle(this HtmlHelper htmlHelper, string parameter) { } 

Then call the helper method from your view (I'm not sure if this is your goal?):

 @Html.BuildFavoritesTitle("myParameter") 

Also, if its a control or any markup you are trying to create in the html helper, consider using MvcHtmlString as the return type.

+1
source

All Articles