Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change title of aspx page dynamically on page load

I had set of ASPX pages in which each page had different titles, but I want to put default title for pages which don't have a title. The default title must be configurable.

like image 415
Randhi Rupesh Avatar asked Jun 07 '13 11:06

Randhi Rupesh


People also ask

How do I change the title of a page?

Change the Web Page TitleIn the Folder List, right-click the page you want to change, and then click Properties. The Properties dialog box opens, displaying the General tab with the current title selected. Type a new name for the title. Click OK.

How do you change the title of a Web page using JavaScript?

Use the querySelector() Method to Change the Page Title in JavaScript. We can use the document. querySelector() method to pick elements in a document. The title element can be chosen by giving the title element a selector parameter and retrieving the page's main title element.


2 Answers

If this is classic ASP.NET (not MVC) and you are using MasterPage then you can set default title in Page_Load event in MasterPage:

protected void Page_Load(object sender, EventArgs e)
{
      if (string.IsNullOrEmpty(Page.Title))
      {
           Page.Title = ConfigurationManager.AppSettings["DefaultTitle"];  //title saved in web.config
      }
}
like image 137
gzaxx Avatar answered Oct 14 '22 08:10

gzaxx


I had a similar problem and none of these solutions worked well for me. The problem stems from the order control events fire for a page. In my case, I had some code that needed to be in the Page_load event (this was because that is the first event where we have a Request object to work with). That code also needed to run before the title could be set. Other pages in my site were able to simply set the desired Title in the page Ctor but because this page needed to interrogate the response object for information first, it was a problem. The problem with this is that the master page has already created the page header section by the time we get to the Page_load event and I didn't want junk in my Master page that was only required for a single page on my site. My simple hack to overcome this issue was to insert a bit of javascript inline in the content portion of the page:

<asp:Content ID=BodyContent ContentPlaceHolderID=MainContent RunAt=Server>
    <script type="text/javascript">
        document.title='<%=Title%>';
    </script>

    ... the rest of the content page goes here ...

</asp:Content>

With this in place, you are free to set the Title in the Page_Load event and it'll be set as soon as this line of code has downloaded. Of course, my site already has a JS requirement so if you're trying to avoid that then this is not going to work for you.

like image 29
krowe2 Avatar answered Oct 14 '22 09:10

krowe2