-1

I have a method inside a controller that creates ViewData. For example this one

private void CreateFKViewData(OSQDCOL osqdcol, OSADCOL osadcol, IList<OSADCOL> targetTBLcols)
{
        ...
ViewData[osadcol.ColName] = new SelectList(SelectListItems, "key", "value", SelectListItems.First().Key);
}

If that method is placed inside the controller everything works as expected. I want to move that method outside my controller and place it into a different class in my BLL layer. The problem is that ViewData is not accessible outside the scope of the controller.

Any ideas?

Christoph Adamakis
  • 865
  • 2
  • 9
  • 26

1 Answers1

1

I'm assuming you're using ASP.NET MVC and C#. Not sure it's a great idea to spread around concerns that a controller would normally do into classes outside of the controller, but suffice to say that the reason for your issue is that ViewData is made available by the fact that your controller class inherits from Controller which in turn inherits from ControllerBase (which is where ViewData is provided). So let's say you wanted to call a method in another class from your controller, and you wanted that method to be able to manipulate ViewData. Consider the following:

public class TestController : Controller
{
    // GET: Test
    public ActionResult Index()
    {
        var externalclass = new SomeRandomClass(this);
        externalclass.DoStuff();
        return View();
    }
}

public class SomeRandomClass
{
    ControllerBase _callingController = null;
    public SomeRandomClass(ControllerBase callingController)
    {
        this._callingController = callingController;
    }
    public void DoStuff()
    {
        this._callingController.ViewData["hello"] = "world";
    }
}
Daniel Graham
  • 399
  • 3
  • 13
  • That seems to work but how am I going to modify this in order to work using Dependency injection and especially autofac? – Christoph Adamakis Feb 26 '15 at 21:21
  • Well that kind of depends on how you're using DI with regard to your controllers? In the example I gave, you could have your IoC inject whatever it needs into the constructor of your Controller and then do whatever you need from there in like fashion. If this doesn't work for you, you might consider not using the ViewData construct and instead use a ViewModel pattern. – Daniel Graham Feb 26 '15 at 23:14