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");
}
}
}