MasterPage - Downside to referencing Controls as properties?
In my ASP.Net MasterPage I sometimes have controls that need to be accessed by m开发者_运维技巧ost Pages. Now instead of using this to access the control
((Label)this.Page.Master.FindControl("lblBreadCrumb")).Text = "foo";
I tend to put a Property in the MasterPage with a reference to the Control, set the @MasterType directive in the Page and access the control like this:
this.Master.BreadCrumb.Text = "foo";
I find this approach much easier to use, but I never actually saw someone do it like this so I wonder if there is any good reason against it that I am missing?
Using properties is a much better idea than using FindControl
for several reasons, I'm glad that you're using this approach!
The most compelling reason to use properties is lets say you change the name of a control, or remove it all together. Now, you have a compiler error, which is much easier to spot. For example, if you rename lblBreadCrumb
and you're using FindControl
, the compiler will not catch this error, and instead your app will fail at run time. Catching errors at compile time is a great feature of a language.
The reason why you don't see many other developers doing this is because good OO design is hardly ever found in Web Forms unfortunately.
No, it's a great approach when many pages will be accessing it.
Sometimes, I may abstract it a little more. For example, instead of simply accessing the control directly, I may just make a property on the master page like BreadCrumbText.
精彩评论