ASP.NET 获取母版页 上控件的值
程序员文章站
2022-04-06 16:57:23
...
1.在前台控件上 增加一个属性 AutoPostBack=true (有的控件支持),那么这个控件的值会自动回传。
2.在master.cs 中 添加代码 让选择项的值 为公开。
public string MasterValue {
get { return this.radio0.SelectedValue; }
}
radio0是 radioButtonList控件
2.可以通过回传,在子页面中,用 this.master指定 属性,和设置。(master需要强制类型转换)
3.可以通过this.matser.findControl(id),获取 母版控件(Control类型),需要强制类型转换。
下面上代码:
Site1.Master
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication4.Site1" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="txtCon" AutoPostBack="true"></asp:TextBox><br />
<asp:RadioButtonList runat="server" AutoPostBack="true" ID="radio0">
<asp:ListItem Value="0">学生族</asp:ListItem>
<asp:ListItem Value="1">上班族</asp:ListItem>
</asp:RadioButtonList>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Site1.Master.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class Site1 : System.Web.UI.MasterPage
{
public string MasterValue {
get { return this.radio0.SelectedValue; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
WebFrom1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="btnset" runat="server" Text="设置" OnClick="btnset_Click" />
<asp:Label runat="server" ID="label1"></asp:Label>
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//通过this.Master.属性 获取(属性需要 public)
//Matser 需要强制类型转换
String str = ((Site1)this.Master).MasterValue;
if (str == "0")
{
label1.Text = "您选择了学生族";
}
else
{
label1.Text = "您选择了上班族";
}
}
protected void btnset_Click(object sender, EventArgs e)
{
//通过this.FindControl获取模板控件(控件需要强制类型转换)
TextBox box = (TextBox)this.Master.FindControl("txtCon");
box.Text = "xx";
}
}
}
上一篇: python基础语法-温度转换