How to dynamically change aspx page title on page load

I had a set of ASPX pages in which each page had different names, but I want to set a default title for pages that don't have a title. The default header must be configured.

+6
source share
5 answers

If this is classic ASP.NET (not MVC) and you are using MasterPage , then you can set the default header in the 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 } } 
+11
source

You can do it:

Set the aspx header to something like this

 <HEAD> <TITLE ID=CaptionHere RUNAT="server"></TITLE> </HEAD> 

And in the code, force this inside the page load event:

 if(!IsPostBack) { myCaption.InnerHtml = "Hope this works!" } 

I hope this helps you

+5
source

I had a similar problem and none of these solutions helped me. The problem is related to the fire of order management events for the page. In my case, I had the code that should have been in the Page_load event (this was because this is the first event in which we have a Request object to work with). This code also needs to be run before the header can be set. Other pages on my site were able to simply set the desired title on the Ctor page, but since this page was needed to pre-poll the response object for information, this was a problem. The problem is that the main page has already created a page header section by the time we get to the Page_load event, and I did not want to have an unwanted file on my main page that was required for only one page on my site. My simple hack to solve this problem was to insert a javascript part into the page content bar:

 <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 place, you can set the Title in the Page_Load event, and it will be set as soon as this line of code is loaded. Of course, my site already has a JS requirement, so if you try to avoid this, this will not work for you.

+1
source

In the main page code, you can set [this.Title = "Whatever";] or you can also specify the default title in HTML.

0
source
 protected void Page_Load(object sender, EventArgs e) { Page.Title = title(); } private string title() { SqlConnection con = new SqlConnection(cs); string cmdstr = "select * from title where id = 2"; SqlCommand cmd = new SqlCommand(cmdstr, con); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); con.Open(); da.Fill(dt); con.Close(); if (dt.Rows.Count > 0) { string title = dt.Rows[0]["title"].ToString(); } return title; } 

This is useful

0
source

Source: https://habr.com/ru/post/946767/


All Articles