Mehdi
Mehdi

Reputation: 105

How can I access viewbag in a class library?

I have a solution that have a class library and a mvc project.

I need to have a method in the class library that change viewbag. But i cant access to viewbag from class library project.

What should I do ?

Upvotes: 2

Views: 3209

Answers (2)

John Lord
John Lord

Reputation: 2185

You can't. ViewBags don't extend anything that can be passed as a parameter. I'm referring specifically to the viewbag itself, not the variable properties. You can pass those, as objects. You have other options though. You could replace the ViewBag with a session variable. Session variables can be directly accessed inside models by referencing them like this:

System.Web.HttpContext.Current.Session["error"] = "error!";

and of course you can easily reference this in an index page or controller.

Upvotes: 1

Dan But
Dan But

Reputation: 658

Have you tried passing the Viewbag into the Method?

Where are you using the class library in your MVC project?

Update: You are calling the class library from the controller

Here is an example if your viewbag is for ice cream and your class library calculates price.

  1. In controller and viewbag is set to chocolate.
  2. Call class library and pass Viewbag.Icecream.ToString()
  3. Return from class libray "$1.50"
  4. Pass the returned data to the view

Upvotes: 0

Related Questions