【发布时间】:2016-06-03 05:39:13
【问题描述】:
我在堆栈上搜索的许多答案都与旧版本的 asp.net mvc 有关,所以我想发布一个新问题,因为它与在每个页面加载时运行一个函数有关特定于 mvc5 。我基本上想在每次页面加载时运行一个查询。
我read 以下是与 mvc 3 相关的,但它有点令人困惑,并没有真正提供任何帮助。我想将以下代码移动到“全局”函数中:
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");
}
}
}
更新
在this article 和this article 的帮助下,我得以完成这项工作。我不想将其标记为重复 b/c 我真的不知道在哪里创建这些文件(例如模型文件夹、控制器文件夹等)。我对 MVC 还是很陌生,所以如果有人不同意,我很乐意将其标记为骗子。以下是我用来解决问题的步骤。
在模型文件夹“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();
}
}
}
}
然后我将它添加到我的 FilterConfig.cs 文件中,如下所示:
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());
}
}
}
控制器看起来像这样
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");
}
}
}
【问题讨论】:
-
很多不同的方法来实现这一点。
OnActionExecuting只是一个:msdn.microsoft.com/en-us/library/… -
@mxmissile 谢谢!我更新了我的答案以使用
OnActionExecuting。 -
@MikeDebela 我使用了您建议的文章作为可能的欺骗,但它与另一篇文章结合使用。我在回答中表示,我还不愿意将此标记为欺骗,但请告诉我您的想法
标签: c# asp.net asp.net-mvc asp.net-mvc-5