asp.net-mvc - 如何根据用户在MVC 4中过滤结果

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有一个自定义身份验证,当用户登录时,我将必要的信息保留在 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();
}

关于TempDataTempData.Keep()的关键点
  • TempData中的项目只有在阅读后才标记为删除。
  • 通过调用TempData可以取消标记TempData.Keep(key)中的项目。
  • RedirectResultRedirectToRouteResult始终调用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/

    相关文章:

    c# - 如何配置 Visual Studio 2017 以在 ASP.Net MVC https 站点中公开非加密端口

    c# - 无法确定类型为 'Npgsql.NpgsqlFactory' 的提供程序工厂的提供程序名称

    asp.net-mvc - 使用基于插件的架构和 ASP.NET MVC 开发 Multi-Tenancy 应用程序

    c# - 如何为整个 Razor View 禁用 HTML 编码

    asp.net - ASP.Net MVC Cookies不持久

    asp.net-mvc - 为什么输出缓存不适用于我的 ASP.NET MVC 4 应用程序?

    sql-server - MVC 持久化集合 ViewModel(更新、删除、插入)

    c# - 服务层和存储库性能问题

    c# - 身份服务器 4 : Proper logout from MVC Client

    javascript - 从未在 ApiController 中调用 Post 方法