MasterPage(母板页)的不一般用法

原先使用母板页的时候都是在aspx页面前面加上一条编译指令 ,指定该页面的母板页是某某.

其实我们也可以通过page 对象的MasterPageFile属性来指定具体使用的是哪个文件.

这个指定过程一般放在page对象的PreInit事件中 例如:

 public class BasePage:Page
{
public BasePage()
{
PreInit += Set_MasterPage;
}
public void Set_MasterPage(object sender, EventArgs e)
{
this.MasterPageFile = Request.Path+"...../jj.Master";
}
}

这样继承自该类的对象就都以这个jj.Master母板为了.

在母板页的代码文件(.cs)中我们可以定义各种字段属性 给前端的模版(.Master)使用.

这样有一个好处就是 链接以及路径部分可以被分离出来. 发布时一套,测试时一套.

甚至可以大段的的分离你想要分离的.

这些分离的东西可以是保存在web.config文件中的内容.

这些分离的部分可以做为母板代码文件的一个字段.例如

 protected TemplateInfo TemplateInfo
{
get { return TemplateInfo.Instancel; }
}
public class TemplateInfo
{
/// <summary>
/// 单例
/// </summary>
private static readonly TemplateInfo Instance = new TemplateInfo();
public static TemplateInfo Instancel
{
get { return Instancel; }
}

private static DateTime scriptTempLastTime;
private static String scriptHtml;

public static String ScriptHtml
{

get
{
string path = "";
DateTime lastDT = File.GetLastWriteTime(path);
if (scriptTempLastTime < lastDT || string.IsNullOrEmpty(scriptHtml))
{
scriptTempLastTime = lastDT;
scriptHtml = File.ReadAllText(path);
}
return scriptHtml;
}


}
#region ctor
/// <summary>
/// ctor
/// </summary>
private TemplateInfo()
{

}
#endregion
}


总结 这中做法的好处主要是 只需要继承一下就可以获得一个模板 更换母板也后只需修改一处地方即可 ,一个母板对应一个继承自page类的类.

母板类中的变化量也可以被分离到外部文件当中.


原文地址:https://www.cnblogs.com/wxzl/p/2333163.html