If the master page has a label with the id label1 how do I control that id in the content page. The id is not passed down so i can't control it inherently. For example if i have a control with the id contentLabel i can access it code by just typing contentLabel.(whatever i'm doing)
Get ID of Master Page object in Content Page
Asked Answered
@antisanity I was thinking it was a technical term - funny! I too thought MasterType should automatically appear in the MarkUp. I believe they do this because you may dynamically set the master page in code-behind as they are "loosely coupled". Selecting the MasterPage when creating a new page only serves to set the "default" MasterPage. So declaring MasterType is like saying you promise not to assign dynamic MasterPages (and in return you are rewarded with Strongly Typed Intellisense). –
Eurypterid
Here are two options:
1: make sure your content aspx specifies MasterType:
<%@ MasterType VirtualPath="~/yourMasterPageName.master" %>
Doing this lets your content page know what to expect from your master-page and gives you intellisense. So, now you can go ahead and expose the label's Text property on the master page's code-behind.
public string ContentLabelText
{
get { return contentLabel.Text; }
set { contentLabel.Text = value; }
}
Then you can access it in your content page's code-behind page ala:
Master.ContentLabelText = "hah!";
or, 2: You can access the label via FindControl() like so:
var contentLabel = Master.FindControl("contentLabel") as Label;
is there a better practice or is this the only way? just curious –
Nonobjective
Thanks, it works perfect. I'm new to .NET. Programmed for awhile, but never in .NET or web development. –
Nonobjective
@Nonobjective The idea of making a protected member public this way has a "bad code smell" to me. See Jeff Atwood's description of "Indecent Exposure" here: codinghorror.com/blog/2006/05/code-smells.html. If all you need to do is change the text then I'd use a getter and setter on only the text. i.e. public string ContentText {get{return contentLabel.Text;} set{contentLabel.Text=value;}} –
Eurypterid
© 2022 - 2024 — McMap. All rights reserved.