如何在MVC 4基于用户过滤后的结果 [英] How to Filter result in MVC 4 based on user
问题描述
我有一个自定义authenticantion,当用户登录时,我一直在会话/缓存的必要信息...
I have a custom authenticantion, when user logs in, I keep the necessary information on Session/Cache...
所以,我有一些看法与下拉菜单必须显示按用户ID筛选的数据...
我倒是喜欢知道什么最好的方式来这一结果过滤...
So, I have some Views with DropDowns that must show data filtered by User id... I´d like to known what the best way to filter that result...
1 - 直接在控制器
1 - Direct on Controller?
...
Model.MyList = repository.GetAll().Where(x => x.User.Id == userId);
return View(Model);
2 - 创建一个动作过滤器(我怎么能做到这一点,而不从数据库查询不必要的数据)
2 - Creating an action filter (How can I do that without querying unnecessary data from DB)
3 - 其他方式
1的问题是,我有一个具有相同的下拉一些意见,所以我将不得不重复同样的code。
The problem with 1 is that I have several views that have the same dropdown, so I will have to repeat the same code.
推荐答案
功能
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 code>和
TempData.Keep()
Key point about TempData
and TempData.Keep()
- 在
的TempData code>的项目将只标记为删除已阅读了。
- 在
的TempData code>项目可以通过调用无标记
TempData.Keep(键)
。 -
RedirectResult
和RedirectToRouteResult
总是调用TempData.Keep()
保留在的TempData code项>。
- Items in
TempData
will only tagged for deletion after they have read. - Items in
TempData
can be untagged by callingTempData.Keep(key)
. RedirectResult
andRedirectToRouteResult
always callsTempData.Keep()
to retain items inTempData
.
您可以使用会话
变量也只有主要问题是,会话
变量都非常繁忙,<$比较C $ C>的TempData code>。最后,你能够保持整个数据的控制器/地区的也。
You could use Session
Variable also, Only major problem is that Session
Variable are very heavy comparing with TempData
. Finally you are able to keep the data across Controllers/Area also.
的TempData code>工作在新的选项卡/视窗的也一样,
会话
变量一样。
TempData
works in new Tabs/Windows also, like Session
variable does.
您可以缓存
数据某些变量,可以再次重复使用在了的TempData code>做了同样的方式。
You can Cache
the Data in some variable and can be reused again In the same manner done for TempData
.
这篇关于如何在MVC 4基于用户过滤后的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!