关于母版页的按钮事件
参考:http://topic.csdn.net/u/20120309/13/96d8c42f-6bcc-4acf-89e7-8015cac777ba.html?37024
解决这个问题,首先要明白一件事情,masterpage只是一个容器,它将要装载很多网页,Div是放在哪一个网页内,要设法让masterpage知道。比如P1.aspx页内有Div id为Div1, P2.aspx也有一个Div id 为Div1。masterpage不知道你要显示那页的Div1. Div只想要显示与否,由谁来控制它不管,可以由page或是masterpage都有可能去控制它。
因此,你可以写一个接口,它有一个方法并带一个参数:
ISetable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ISetable
/// </summary>
namespace Insus.NET
{
public interface ISetable
{
void Setting(bool show);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ISetable
/// </summary>
namespace Insus.NET
{
public interface ISetable
{
void Setting(bool show);
}
}
如果是要P1的Div需要控制,那就在P1.aspx.cs实作这个接口,当然如果是P2.aspx,那就是P2.aspx.cs实作接口。
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class P1 : System.Web.UI.Page,ISetable
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Setting(bool show)
{
this.Div1.Visible = show;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class P1 : System.Web.UI.Page,ISetable
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Setting(bool show)
{
this.Div1.Visible = show;
}
}
最后,你可以确定由谁来控制它。是masterpage还是page,那就在这容器的按钮Click事件中写:
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ISetable d = (ISetable)this.Page;
d.Setting(true);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ISetable d = (ISetable)this.Page;
d.Setting(true);
}
}
演示:
Demo代码:
http://download.cnblogs.com/insus/ASPDOTNET/mpEvent.rar
以下内容添加于2012-03-09 17:10:
重构如下,把两个铵钮整合为一个,效果:。
click事件:
View Code
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ISetable d = (ISetable)this.Page;
switch (btn.Text)
{
case "开":
btn.Text = "关";
d.Setting(true);
break;
case "关":
btn.Text = "开";
d.Setting(false);
break;
}
}
{
Button btn = (Button)sender;
ISetable d = (ISetable)this.Page;
switch (btn.Text)
{
case "开":
btn.Text = "关";
d.Setting(true);
break;
case "关":
btn.Text = "开";
d.Setting(false);
break;
}
}