When I asked recently a question about how To retrieve a control in a Master Page from Content Page. Many peoples suggest me to use this code from my Content Page:
Label lbl = this.Master.Page.FindControl("uxLabel") as Label;
//Note any server controls defined in the master page could be not be accessible even after a cast is performed, because they could be marked as protected
This approach certainly works, I also realize that is available a strongly-typed solution that doesn't involve casting the Master property.
In the Master Page place:
public Label HeaderLabel
{
get { return uxLabel; }
}
Using a MasterType in the Content Page:
<%@ MasterType VirtualPath="~/Templates/WebsiteMasterPage.master" %>
Now it is pretty easy find the control from the Content Page:
protected void Page_Load(object 开发者_StackOverflowsender, EventArgs e)
{
this.Master.HeaderLabel.Text = "Any Text here!";
}
I would like to know:
- what do you think about this approach? any other solution?
Thanks for your time
My answer is "why not?".
Both are for me good approaches but first needs less coding in order to get started with it, since you don't need to initialize any class field and design properties. But control must be found during run-time.
Second approach, call it "typed approach", is just cast to specific master page class and you get access to any class-specific member.
What would be the main problem of "typed approach"? You need a reference to the class library (assembly) in order to access to such master page's members, which wouldn't be desirable in some scenarios. For example, you've a control library and you want to access a mandatory master page's control which provides some behaviors needed to work with some library's control. You would need to reference your web client assembly, but you can't do that because you reference your control library in the web client itself, and this is a circular reference.
Tools, approaches are there for use in specific scenarios. Why not? answer can be expanded to why not to use "typed approach" if it's needed and your scenario is compatible with that concept?.
精彩评论