Ido Ran
Ido Ran

Reputation: 11414

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

I've wrote extension method to HtmlHelper that is invoked from a master page that need to access the ViewBag to get information set by the page.

This is the method signature:

public static string BuildFavoritesTitle(this HtmlHelper htmlHelper) { }

I've notice that inside the method if I access

htmlHelper.ViewContext.ViewBag

I get empty ViewBag, but if access

htmlHelper.ViewBag

I get the "correct" ViewBag. By correct I mean ViewBag with the items added in the inner Page.

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

Upvotes: 4

Views: 1389

Answers (1)

sambo
sambo

Reputation: 221

What purpose are you setting values in a view data dictionary? Is it some sort of property to determine how to render a control?

Consider adding additional parameter/s to 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 aim?):

@Html.BuildFavoritesTitle("myParameter")

Also, if its a control, or some sort of markup you're trying to build in your html helper, consider using MvcHtmlString as the return type.

Upvotes: 1

Related Questions