How to Filter result in MVC 4 based on user

前端 未结 7 993
面向向阳花
面向向阳花 2020-12-13 22:26

I have a custom authenticantion, when user logs in, I keep the necessary information on Session/Cache...

So, I have some Views with DropDowns that must show data fil

7条回答
  •  孤街浪徒
    2020-12-13 22:41

    Approach - 1

    Function

    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.
    }
    

    Filter Method

    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 Action Method

    [MyActionFilter] 
    //Whenever Action Method will execute. We will check TempData contains 
    //Data or not.
    public ActionResult Index()
    {
        return View();
    }
    

    Key point about TempData and TempData.Keep()

    1. Items in TempData will only tagged for deletion after they have read.
    2. Items in TempData can be untagged by calling TempData.Keep(key).
    3. RedirectResult and RedirectToRouteResult always calls TempData.Keep() to retain items in TempData.

    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 works in new Tabs/Windows also, like Session variable does.

    Approach - 2

    You can Cache the Data in some variable and can be reused again In the same manner done for TempData.

提交回复
热议问题