Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag in static method of controller

I am new to mvc and I load ViewBag in a method of controller as,

HomeController: Controller
{
    Public ActionResult Index()
    {
        loadViewBag();
        return View();
    }

    public void loadViewBag()
    {
      ViewBag.aaa = "something";
    }
}

It works fine.

What is my problem is, Now I want to call loadViewBag() method form another controller( say Account) so that I can reuse same method and need to make loadViewBag() method static due to some static variables as: public static void loadViewBag() If I make loadViewBag method static, there appear error on ViewBag " An object reference is required for the non-static field, method, or property 'System.Web.Mvc.ControllerBase.ViewBag.get' ".

Is there any solution/suggestion.

Thank You.

like image 581
link2jagann Avatar asked Jun 04 '26 03:06

link2jagann


2 Answers

Just make it an extension method of ControllerBase e.g.

public static void ControllerExt
{
    public static void LoadViewBag(this ControllerBase controller)
    {
        controller.ViewBag.aaa = "something";
        ...
    }
}

That way you can use it in any controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        this.LoadViewBag();
        return View();
    }
}

public class AccountController : Controller
{
    public ActionResult Index()
    {
        this.LoadViewBag();
        return View();
    }
}

If its only specific to some controllers then it would be more flexible to pass the ViewBag property in e.g.

public static class ControllerHelper
{
    public static void LoadViewBag(dynamic viewBag)
    {
         viewBag.aaa = "something";
    }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ControllerHelper.LoadViewBag(ViewBag);
        return View();
    }
}
like image 178
James Avatar answered Jun 07 '26 10:06

James


ViewBag is a property of your controller (more specifically of ControllerBase), and since a static method has no knowledge of a class instance, you can't access it.

You could pass the controller instance to the method if you want to use a static method or even make it an extension method, but depending on your problem, this solution could be sub-optimal. You may be able to get a better answer if you add more details to your question.

Public ActionResult Index()
{
    this.loadViewBag();
    return View();
}

public static void loadViewBag(this ControllerBase target)
{
    target.ViewBag.aaa = "something";
}
like image 44
user247702 Avatar answered Jun 07 '26 09:06

user247702