首先它是一个具有返回类型为ViewResult的一个方法,也就是说,我们可以通过返回ViewResult对象来代替View()方法,下面的操作是合法的
ViewData.Model = model;
return new ViewResult
{
ViewName = viewName,
MasterName = this.MasterFile,
ViewData = ViewData,
TempData = TempData
};
它在一般情况下等同于return view(model),这是微软为我们封装好的方法,让我们省去了不少代码,它的view(object model)方法原型可能是这样的
protected internal ViewResult View(object model)
{
ViewData.Model = model;
return new ViewResult
{
ViewName = viewName,
MasterName = this.MasterFile,
ViewData = ViewData,
TempData = TempData
};
}
呵呵,我们有时,希望在后台通过调用masterfile的方法来动态改变模版页,可以这样来实现
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
};
}
}
/// <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/StudentCenter.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:
masterPageFile = "~/Views/Shared/StudentCenter.Master";
break;
}
return masterPageFile;
}
}
而在同一个controller中,如果你的View视图不希望去应用任何模板页,可以写这样一个方法,呵呵
/// <summary>
/// 返回没有母板页的视图
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
protected ViewResult ViewNotMasterFile(object model)
{
ViewData.Model = model;
return new ViewResult
{
MasterName = string.Empty,
ViewData = ViewData,
TempData = TempData
};
}
呵呵,多么灵活法,(因为ASCX视图不能有母板页的,呵呵)