1

Many of the answers i've searched for on stack are related to older versions of asp.net mvc, so i wanted to post a new question as it relates to running a function on every page load specific to mvc5. i basically want to run a query every single time a page loads.

I read the following as it related to mvc 3, but it was a little confusing and didn't really provide any help. I'd like to move the following code into a "global" function:

namespace MVC5.Controllers
{
  public class LoginController : Controller
  {
    private LoginDataContext context;        

    public LoginController()
    {
        context = new LoginDataContext();
    }   

    public ActionResult Index()
    {
        int item=1;
        List<int> foo = context.ExecuteQuery<int>("SELECT foo from bar where id={0}", item).ToList();            
        foreach (var item in isUpdating)
        {      
          //if logic .....
          return PartialView("DbUpdate");
        }
        return RedirectToAction("Index", "Home");
    }
  }
}

UPDATE

I was able to get this to work with help from this article and this article. I do not want to mark this as a duplicate just yet b/c i didn't really know where to create these files (e.g. models folder, controllers folder, etc). i'm still fairly new to MVC, so if anyone disagrees, i'm happy to mark this as a dupe. Here were the steps i used to resolve my issue.

Create in models folder "MyActionFilter.cs":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC5.Controllers;

namespace MVC5.Models
{
    public class MyActionFilter : ActionFilterAttribute
    {       
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {  
            var dbUpdate = new DbUpdateController();
            int nomz=1;
            if (nomz==1)
            {
               filterContext.Result = dbUpdate.Index();
            }
        }
    }
}

Then i added this to my FilterConfig.cs file looks like now:

using System.Web;
using System.Web.Mvc;
using MVC5.Models;

namespace MVC5
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new MyActionFilter());  
        }        
    }
}

Controller looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC5.Controllers
{
    public class DbUpdateController : Controller
    {
        // GET: DbUpdate
        public ActionResult Index()
        {
            return View("DbUpdate");
        }       

    }
}
Community
  • 1
  • 1
jellz77
  • 324
  • 4
  • 15
  • 1
    Lots of different ways to accomplish this. `OnActionExecuting` is just one: https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting%28v=vs.118%29.aspx?f=255&MSPPError=-2147217396 – mxmissile Jun 02 '16 at 19:03
  • @mxmissile thanks! i updated my answer to use `OnActionExecuting`. – jellz77 Jun 02 '16 at 21:40
  • @MikeDebela i used the article you had suggested as a possible dupe, but it was used in conjunction with another article. i stated in my answer that i didn't feel comfortable marking this as a dupe just yet, but let me know your thoughts – jellz77 Jun 02 '16 at 21:42

1 Answers1

2

For something like this I like to create custom attributes, then you can define it on the controller and/or action levels so you get the flexibility of NOT using it in certain places.

If that's interesting to you

https://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute(v=vs.118).aspx

I also forgot about global action filters http://weblogs.asp.net/gunnarpeipman/asp-net-mvc-3-global-action-filters

and their overrides in mvc5

http://davidhayden.me/blog/filter-overrides-in-asp-net-mvc-5

They are very simple. Define an action filter as normal and in your Application_Start() add

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

and in your App_Start\FilterConfig.cs file

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new YOURCUSTOMFILTER );
     }
Paul Swetz
  • 2,234
  • 1
  • 11
  • 28
  • unfortunately, i have a ton of controllers and need to run this method on every page load – jellz77 Jun 02 '16 at 19:27
  • No ajax actions or anything like that? Even in that case you would only need to tag each controller once with the attribute on the controller class definition. ActionFilters can be specific to a single action or if the controller is tagged then all actions in the controller get it. – Paul Swetz Jun 02 '16 at 19:40
  • Also see update on global filters – Paul Swetz Jun 02 '16 at 19:41
  • thanks, paul! i used your filters suggestions in conjunction with some other coding changes. see update above – jellz77 Jun 02 '16 at 21:43
  • Glad it worked out. We usually put them in a "Filters" folder in the MVC project just to be obvious or an "attributes" folder in a referenced project if we are making lots of attributes. – Paul Swetz Jun 03 '16 at 12:20