正在阅读:Asp.net1.1实现仿2.0 MasterPage效果Asp.net1.1实现仿2.0 MasterPage效果

2005-09-21 10:10 出处:PConline 作者:Kgdiwss 责任编辑:moningfeng

  相关推荐用Asp.net制作顶部导航控件      ASP.Net开发新手常见问题备忘录

  在Asp.net 2.0中,提供了一个MasterPage的功能,它可以让我们很方便的完成页面的整体结构相同的网站,而且后期修改界面的时候只要修改一下MasterPage即可,无需一个个界面进行修改,这样就大大的方便了开发人员.其实类似这种技术在Asp.net1.1中也可以实现.

一、 思路分析
  对于可以用MastetrPage的网站来说,它的页面结构大部份是一至的,比如顶部、底部都是一样的,只不过左右侧显示的内容不同。这个时候,你不妨把左右两侧的内容也分别放在用户控件中,然后根据当前的访问地址来动态加载用户控件,这样到时候只要修改动态加载的用户控件的内容,或是MasterPage的框架,即可实现修理网站的目的。

二、 实现过程
  首先取得当前访问的文件地址,代码如下:

//取得当前访问的路径
string strRequestUrl = Request.Url.AbsolutePath.ToString();
//取得当前访问的文件名,并转换成小写
string strNowViewFile = strRequestUrl.Substring((strRequestUrl.LastIndexOf(@"/") + 1)).Trim().ToLower();


  然后点击“添加添加Web用户控件”新建三个用户控件,分别命名为MasterPage.ascx、Head.ascx和Foot.ascx,在MasterPage.ascx中添加一个三行两列的表格,然后将Head.ascx和Foot.ascx控件拖到MasterPage.ascx中,同时在左右两侧均添加一个PlaceHolder控件,分别命名为hldLeftControl和hldRightControl,完成后效果如下:

Head.ascx

hldLeftControl

hldRightControl

Foot.ascx


  此时只要将MasterPage.ascx拖到具体的页面中,比如Index.aspx,运行后就会显示顶部、底部的内容。接下来要根据当前访问的文件地址,确定动态加载哪些用户控件到左右两侧位置,这部份操作在MasterPage.ascx.cs中完成。代码如下:

switch(strNowViewFile)
{
//如果当前访问的是首页
case "index.aspx":
//创建用户控件类的对象,类名与用户控件的名称是相同的
Control_Index_IndexRightControl indexRightControl;
//加载用户控件
indexRightControl = (Control_Index_IndexRightControl)Page.LoadControl("Control_Index_IndexRightControl.ascx");
//在右侧的PlaceHolder控件中显示用户控件
plhRightControl.Controls.Add(indexRightControl);
break;
//加载会员注册部份
case "Register.aspx":
Control_Login_Register register;
register = (Control_Login_Register)Page.LoadControl("Control_Login_Register.ascx");
plhRightControl.Controls.Add(register);
break;
default:
indexRightControl = (Control_Index_IndexRightControl)Page.LoadControl("Control_Index_IndexRightControl.ascx");
plhRightControl.Controls.Add(indexRightControl);
break;
}


  添加了以上代码后,如果访问的页面是index.aspx,在index.aspx页右侧,就会加载Control_Index_IndexRightControl.ascx控件的内容,如果访问的是Register.aspx页,右侧就会加载Control_Login_Register.ascx控件的内容.这样就实现了类似MasterPage的功能.

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品