MVC根据用户角色选择模版页master

首先,我们要重写一个View方法,才能更好的返回指定的master页面

对于前台controller来说,我们建立一个它的基类

 /// <summary>
    /// 前台Controller的基类,
    /// 提供一些共同属性和方法
    /// Created By : 张占岭 
    /// Created Date : 2011-10-17
    /// Modify By:
    /// Modify Date:
    /// Modify Reason:
    /// </summary>
    public abstract class BaseController : Controller
    {
        /// <summary>
        /// 根据用户角色,返回它的模版页
        /// </summary>
        protected string MasterFile
        {
            get
            {
                return UIHelper.GetMasterPage(Tsingda.XXB.Common.WebSession.UserRole);
            }
        }

        /// <summary>
        /// 重写controller的View方法,使它可以根据用户角色应用指定视图
        /// </summary>
        protected new ViewResult View(string viewName, object model)
        {
            ViewData.Model = model;
            return new ViewResult
            {
                ViewName = viewName,
                MasterName = this.MasterFile,
                ViewData = ViewData,
                TempData = TempData
            };
        }

        protected new ViewResult View(object model)
        {
            return this.View(null, model);
        }
    }

我们根据角色来选择不同的模版页:

 /// <summary>
    /// 前台通用方法
    /// </summary>
    public partial class UIHelper
    {
        /// <summary>
        /// 根据用户角色,得到指定的模板
        /// <param name="role"></param>
        /// <returns></returns>
        public static string GetMasterPage(Tsingda.XXB.Common.CustomEnum.UserRole role)
        {
            string masterPageFile = "";
            switch (role)
            {
                case Common.CustomEnum.UserRole.Student:
                    masterPageFile = "~/Views/Shared/StudentClassCenter.Master";
                    break;
                case Common.CustomEnum.UserRole.Teacher:
                    masterPageFile = "~/Views/Shared/TeacherCenter.Master";
                    break;
                case Common.CustomEnum.UserRole.Parents:
                    masterPageFile = "~/Views/Shared/ParentCenter.Master";
                    break;
                case Common.CustomEnum.UserRole.Agents:
                    break;
                case Common.CustomEnum.UserRole.Visitor:
                    break;
            }
            return masterPageFile;
        }
    }

这样,就可以了,其实这部分代码中,核心功能就是如何让controller里的代码控制页面的母板,这里,我们返回了viewresult对象解决了这个问题

  return new ViewResult
            {
                ViewName = viewName, //view名称
                MasterName = this.MasterFile, //母板文件
                ViewData = ViewData, //viewdata对象
                TempData = TempData
            };

posted @ 2011-10-18 09:50  张占岭  阅读(866)  评论(1编辑  收藏  举报