C# 在asp.net中从母版页到子页获取值
我有一个母版页C# 在asp.net中从母版页到子页获取值,c#,asp.net,session,master-pages,C#,Asp.net,Session,Master Pages,我有一个母版页masterpage.master,其中我在一个变量中存储了一个值 string Name = (string)(Session["myName"]); 现在我想在masterpage.master的子页面中使用“Name”中的值,但不在每个页面上使用session。我能做到吗? 如果是,请告诉我 我正在使用c#和ASP.netwebforms您可以将名称放在控件中,即主页上的文本框中,并在这样的内容页中找到它 // On Master page TextBox mastertx
masterpage.master
,其中我在一个变量中存储了一个值
string Name = (string)(Session["myName"]);
现在我想在masterpage.master的子页面中使用“Name”中的值,但不在每个页面上使用session。我能做到吗?
如果是,请告诉我
我正在使用c#
和ASP.net
webforms您可以将名称
放在控件中,即主页
上的文本框
中,并在这样的内容页中找到它
// On Master page
TextBox mastertxt = (TextBox) Master.FindControl("txtMaster");
// On Content Pages
lblContent.Text = mastertxt.Text;
有关它的更多详细信息,请在上查看此项。您可以从当前页面访问并将其转换为您的类类型:
MyMasterPage master = Master as MyMasterPage;
var value = master.NeededProperity;
在评论中看起来像:
Public属性是一个很好的方法,但是必须在每个内容页(aspx文件)中放置MasterType指令。如果内容页扩展了基类(它扩展了页面),那么同样的强类型也可以在基类CodeBehind中完成。例如:
// MySiteMaster : System.Web.UI.MasterPagepublic
string Message
{
get
{
return MessageContent.Text;
}
set
{
MessageContent.Text = value;
}
}
// MyPage : System.Web.UI.Page
MySiteMaster masterPage = Master as MySiteMaster;
masterPage.Message = "Message from content page";
MessageContent是母版页上的控件。MyPage类可以将消息作为自己的属性公开,或者允许派生类直接访问它。向母版页添加新的只读属性
public string MyName
{
get { return (string)(Session["myName"]); }
}
在内容页的页面声明之后添加此代码(相应地更改母版页文件名和路径)
在aspx页面中使用masterpagetype指令,如下所示
<%@ MasterType virtualPath="~/Site.master"%>
现在,您可以使用“master.[VariableName]”访问母版页的变量。您可以这样尝试:
// Master Page File (Storing the value in label)
string Name = (string)(Session["myName"]);
lblmsg.Text= name;
// cs File
Label str = Master.FindControl("lblmsg") as Label;
TextBox10.Text = str.Text ;
在web用户控件页和母版页之间传递数据
<%@ MasterType virtualPath="~/Site.master"%>
// Master Page File (Storing the value in label)
string Name = (string)(Session["myName"]);
lblmsg.Text= name;
// cs File
Label str = Master.FindControl("lblmsg") as Label;
TextBox10.Text = str.Text ;