Finding a Control in a page from a page base class

◇◆丶佛笑我妖孽 提交于 2019-12-10 14:18:45

问题


Hope you're having a good Friday and stuff... okay, so here's my question:

All my ASPX pages inherit from a base class called BasePage. BasePage inherits from:

System.Web.UI.Page

Now, how do I access/set a control in my aspx page from my page base? I've tried this:

HyperLink hypMainMenu = (HyperLink)Page.FindControl("hypMainMenu");
hypMainMenu.NavigateUrl = AppConfiguration.AppSettings.Urls.MainMenu;

But hypMainMenu is always null - I can't find the bastard. Any ideas? Or is this bad practice and someone can reccommend a better way to do this?

Thanks in advance!


回答1:


Even though what is and is not good practice is very subjective, I must say that trying to access anything from a control from it's base class is bad practice. A base class should only contain code that is relevant for all classes that will inherit it, and how do you know that every page you write in the future will have this control?

A better way to solve your problem (which I assume to be having code for your main menu in only one place) would be to write a UserControl and which you include on every page. If you need to do something specific with that control, you can do it in the UC's CodeBehind.



来源:https://stackoverflow.com/questions/839794/finding-a-control-in-a-page-from-a-page-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!