我有一个自定义身份验证,当用户登录时,我将必要的信息保留在 session /缓存中...
因此,我有一些带有DropDowns的 View ,这些 View 必须显示按用户ID过滤的数据...
我想知道过滤结果的最佳方法是什么...
1-直接在 Controller 上?
...
Model.MyList = repository.GetAll().Where(x => x.User.Id == userId);
return View(Model);
2-创建 Action 过滤器(如何在不从数据库查询不必要的数据的情况下做到这一点)
3-其他方式?
1的问题是我有多个具有相同下拉菜单的 View ,因此我将不得不重复相同的代码。
最佳答案
方法-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);
}
}
Controller 操作方法
[MyActionFilter]
//Whenever Action Method will execute. We will check TempData contains
//Data or not.
public ActionResult Index()
{
return View();
}
关于
TempData
和TempData.Keep()
的关键点TempData
中的项目只有在阅读后才标记为删除。 TempData
可以取消标记TempData.Keep(key)
中的项目。 RedirectResult
和RedirectToRouteResult
始终调用TempData.Keep()
以将项目保留在TempData
中。 您也可以使用
Session
变量,唯一的主要问题是Session
变量与TempData
相比非常繁重。最后,您还可以跨 Controller /区域保留数据。TempData
也可以在新选项卡/Windows中使用,就像Session
变量一样。方法-2
您可以使用一些变量对数据进行
Cache
,并可以按照TempData
的相同方式再次进行重用。
关于asp.net-mvc - 如何根据用户在MVC 4中过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18060445/