我有自定义身份验证,当用户登录时,我在Session / Cache上保留必要的信息…
所以,我有一些DropDowns的视图必须显示按用户ID过滤的数据…
我想知道过滤结果的最佳方法是什么……
1 – 直接在控制器上?
... Model.MyList = repository.GetAll().Where(x => x.User.Id == userId); return View(Model);
2 – 创建动作过滤器(如何在不查询来自DB的不必要数据的情况下执行此操作)
3 – 其他方式?
1的问题是我有几个具有相同下拉列表的视图,因此我将不得不重复相同的代码.
解决方法
方法 – 1
private void userInfo(ResultExecutingContext filtercontext) { if (filtercontext.Controller.TempData[userId.ToString()] == null) filtercontext.Controller.ViewBag.userId = filtercontext.Controller.TempData[userId.ToString()] = repository.GetAll().Where(x => x.Id == userId); else //This will load the data from TempData. So,no need to //hit DataBase. filtercontext.Controller.ViewBag.userId = filtercontext.Controller.TempData[userId.ToString()]; TempData.Keep(); // This will save your Database hit. }
过滤方法
public class MyActionFilter : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext filtercontext) { //Call the Action Method before executing the View and after //executing the Action. userInfo(filtercontext); base.OnResultExecuting(filtercontext); } }
控制器动作方法
[MyActionFilter] //Whenever Action Method will execute. We will check TempData contains //Data or not. public ActionResult Index() { return View(); }
关于TempData和TempData.Keep()的要点
> TempData中的项目只有在读取后才会被标记为删除.
>通过调用TempData.Keep(key)可以取消标记TempData中的项目.
> RedirectResult和RedirectToRouteResult始终调用TempData.Keep()来保留TempData中的项目.
您也可以使用会话变量,唯一的主要问题是会话变量与TempData相比非常繁重.最后,您还可以跨控制器/区域保持数据.
TempData也适用于新的Tabs / Windows,就像Session变量一样.
方法 – 2
您可以在某个变量中缓存数据,并可以再次重复使用.以与TempData相同的方式.