0

I am converting a legacy ASP.Net MVC website to Core, and I used to have all controllers inherit from a BaseController class which was overriding Initialize and setting some properties on the ViewBag. There seems to be no Initialize method now, so I'm doing that through the constructor. However, by the time I get to the Action method, it seems the ViewBag has been reset.

The code is basically like this:

public abstract class BaseController : Controller
{
    protected BaseController()
    {
        ViewBag.Hello = "hello";
    }
}

public class MyController : BaseController
{
    public IActionResult Index()
    {
        var hello = ViewBag.Hello;
        // but hello is null

        return View();
    }
}

Should I be overriding a different method rather than going through the constructor? Where is ViewBag getting reset and what is a better way to work around that?

Savage
  • 2,296
  • 2
  • 30
  • 40
  • "The data you put in the ViewBag/ViewData is only available during the life-cycle of the request within which you populated it" Have a look at [this](https://stackoverflow.com/questions/9186674/viewbag-viewdata-lifecycle/9186855#9186855) . Besides, you can look [this](https://stackoverflow.com/questions/12676924/what-is-the-right-time-for-viewdata-viewbag-session-tempdata) to know more. – Qing Guo Jul 04 '23 at 02:29
  • But in my example it's the same request. However, the ViewBag is being reset within the lifecycle of a single request. – Savage Jul 04 '23 at 06:29
  • How do you excute the MyController ? – Qing Guo Jul 04 '23 at 06:32
  • That's an MVC web page, so you're just hitting a url in your browser, e.g. localhost:8083/My/Index in this example – Savage Jul 04 '23 at 06:37
  • When I test your code , `MyController : BaseController` I will get the Error: AmbiguousMatchException: The request matched multiple endpoints . Do you have ? – Qing Guo Jul 04 '23 at 06:52
  • I appreciate your attempt to assist me, but you have routing issues and this question isn't the right place to resolve those – Savage Jul 04 '23 at 06:54

1 Answers1

0

Try to override OnActionExecuting method :

public abstract class BaseController : Controller
    {
        //protected BaseController()
        //{
        //    ViewBag.Hello = "hello";
        //}
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.Hello = "hello";
           
            base.OnActionExecuting(filterContext);
        }
    }

result:

enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
  • @Savage '' it impossible to set ViewBag in the constructor" Have a look at [this](https://stackoverflow.com/questions/40330391/set-viewbag-property-in-the-constructor-of-a-asp-net-mvc-core-controller) . – Qing Guo Jul 04 '23 at 07:24