基于登录用户将数据传递到查看母版页

时间:2011-04-14 10:27:54

标签: asp.net-mvc asp.net-mvc-3 spark-view-engine

我的mvc应用程序出了问题,mvc 3使用了spark视图引擎。 我想基于HttpContext.User.Identity绑定附加到application.spark(母版页)的下拉列表。 问题是..我应该将包含SelectList的ViewData放置为我的DropDownList数据源? 此下拉列表将在我的应用程序的所有页面中访问。 有一篇关于它的文章:http://www.asp.net/mvc/tutorials/passing-data-to-view-master-pages-cs,但它没有解决我的问题,因为我无法从ApplicationController获得User.Identity。

任何想法?

1 个答案:

答案 0 :(得分:1)

  • 您可以创建自己的基本控制器并覆盖OnActionExecuting方法。

    protected override void OnActionExecuting(ActionExecutingContextfilterContext)
    {
        var userName = User.Identity.Name;
        ViewData["MySelectList"] = new SelectList(AllUsers, "Id", "UserName", userName );
    }
    
  • 您可以创建action filter并覆盖'OnActionExecuting'方法 - 然后将该过滤器应用于每个控制器。

     public class MyCustomActionFilterAttribute : ActionFilterAttribute
     {
       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
         var userName =  filterContext.RequestContext.HttpContext.User.Identity.Name;
          filterContext.Controller.ViewData["MySelectList"] = new SelectList(AllUsers, "Id", "UserName", userName);
       }
     }
    
    [MyCustomActionFilter]
    public class HomeController:Controller
    {....
    }
    
相关问题