What is ct100 and how do I rename it? - asp.net

Working in .net 4.0, it still seems all my input controls have the attribute 'name', with a value that begins 'ct100$...'.
Is there any way to rename this?
I've gone all the way up the control hierarchy, and given each control an ID and set its clientidmode to 'Static' to no avail, even the 'earliest' controls on the page still inherit the prefix.

This is the master page's ID. I change it by adding a Page_Init to my masterpage which sets its id:
Private Sub InitSub(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
ID = "master"
End Sub
This ID is normally empty/null so when it renders it it generates an id (starting at ct100 and going up)
Like #Scott Stafford said, keep it short because it prefixes every client id on your page.
I use words like "mBio", "mHome", etc..

Why rename it? You can, as #Bob Fincheimer describes, but so what? Also, if you DO rename it, keep the new name short, because that name shows up in all generated HTML and all POSTing variables hundreds of times, possibly enough to actually affect performance of your site.

If you want to remove it, look in your web.config for the following tag:
<system.web>
...
<pages ... clientIDMode="*something*">
</pages>
...
</system.web>
Remove the clientIDMode="something" property specification. Just take it out.
** I stole my own answer from here.

Related

Page_Load is firing twice in ASP.NET page

Asp.net page_load function is loading twice.. hence it affects my page performance.
Does anyone know the reason it is loading twice.
No, iam not calling the page load function anywhere...
Just ran into this problem, and thought I would post an answer summarizing what I found, plus my actual issue.
1. img tags with src="" or Image tags with ImageUrl=""
2. Using AutoEventWireup="true" and adding a page handler
3. Having manually added the event handler (more common for C# than VB)
4. Handling both MyBase.Load and Me.Load
5. Variation on the missing img src, body { background-image: url(); }
6. Rewrite rule and missing favicon.ico
and finally my issue....
My page inherited from a class that included a Page Load handler, which inherited from a class with a Page Load Handler.
Public Class C1
Inherits System.Web.UI.Page
Protected Overridable Sub PageLoad(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
Public Class C2
Inherits C1
Protected Overrides Sub PageLoad(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Me.Load
MyBase.PageLoad(sender, e)
End Sub
End Class
Public Class MyPage
Inherits C2
Protected Overrides Sub PageLoad(ByVal sender As Object,
ByVal e As System.EventArgs)
MyBase.PageLoad(sender, e)
End Sub
End Class
I tested this, and if you put a Handles on the method in MyPage, it will get hit 3 times...
It is not you calling the page load function twice, that is the way ASP.NET works. The page posts to itself, thus calling the page_load function, when any Server controls on the page are fired (those which as set to postback).
What you need to do is to put some checks to differentiate between an initial page load and a post back
if(!IsPostBack)
{
//Code when initial loading
}
else
{
// code when post back
}
Please find the solution here........
Check if the Load events have Handlers for Base class and the child class
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load, Me.Load**
If it is just Remove the Me.Load from the event , now check your page. Hope this may be useful and solve your issue.
Once I found the following string in a project:
<link rel="Shortcut Icon" href="#" type="image/x-icon" />
Somebody just did it like he usually does with "a href".
But browser actually tries to get the site icon on each refresh, so it sends a request to the address from href parameter, i.e. to the same page.
So, check this as well.
For me It was a blank image tag.
<img src="#" />
I solved my issue by setting the AutoEventWireUp attribute to FALSE. I got this issue when migrating from .net 1.1 to .net 4.0. Somehow VS2012 reset this attribute to TRUE when I copy the file over from the older version.
Remember to check the IsPostBack value as shown below:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
You can put breakpoints inside this IF block to verify you running Page_Load twice.
If you are seeing Page_Load run twice and each time it is not a postback, then check the OnInit() method for this page.
Verify you are not wiring up the Load handler like below. You will see this code often from code that was migrated from earlier versions of Visual Studio.
this.Load += new System.EventHandler(this.Page_Load);
Remove this if you find it. This assumes that you have the following at the top of the markup for the page.
AutoEventWireup="true"
I had the same problem and Solved.
I Checked my Global.ascx and My rewrite rules.
When the page requested, URL did not have "/" at the end of URL and a redirect happened from "x.com/x" to "x.com/x/" according to my configuration for SEO standards.
So anything works well and your internal links should have "/" at the end of URLs to avoid multiple loads.
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.
Reffer MSDN: enter link description here
Please try making the changes mentioned in this link.
http://social.msdn.microsoft.com/Forums/en/vbgeneral/thread/ccc75925-3460-497c-8471-fcebecd8d061
BTW I googled Page_Load Being called twice
I had the same issue.
It was because of a TreeNode with ImageUrl="".
For me I could get around this calling multiple times by using the PreRender event instead
protected override void OnPreRender(EventArgs e)
This is only called once, even if the onload's and init's are called a million times.
I replaced the Response.Redirect with Server.Transfer because it was suggested to be the new way of doing things. Since then, the pages load twice and the Back-button in Chrome returns to the previous page and immediately back to the current page. I replaced the Server.Transfer with Response.Redirect, and all was back to normal.
I also put this answer on page loads twice due to js code.
For me it was solved by removing
Handles Me.Load
and changing the method like
Protected Overrides OnLoad(...)
For me, this issue cropped up suddenly after the Oct. 2017 Windows update. I noticed that for pages made accessible to anonymous users via a Location element in web.config, it is now necessary to also grant access to any assets referenced by that page, for example images, stylesheets, etc. The below example grants anonymous access to the login page and the 'images' directory (aka folder):
<location path="login.aspx">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
<location path="images">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
Update: I found a second cause of Page_Load being called twice. In old, legacy code, some pages' .aspx.designer.cs files contained inconsistencies that apparently hadn't caused problems until now. Instead of attempting repair, I created new pages, which eliminated the double load event.
I had same issue. I have set AutoEventWireup to false and after that remove the Page.Load += new EventHandler(Page_Load); from the InitializeComponent(). Now it's working.....
I think because of [DefaultEvent("Load")] in System.Web.UI.Page, the default event is Load so you don't need to add it again when your page class is initializing.
I am also experiencing page loading twice. For me, I have deduced that is happening only when aspx page contains <style> with internal css declaration. If I remove that tag, then it loads only once.

VB.NET if button1 caused post back then

I have a situation where I need to ignore parts of page load sub inside a isPostback = true. Basically inside the isPostBack I want something like if button1 caused postback.... do this else do this...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = True Then
If TextBox1.Text <> String.Empty Then
CheckDate()
End If
End If
End Sub
I think what you need is the reference to the control name which triggered the postback.
http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
Implement the solution which is there in the above link (Got it from here.... How to Get Source of postback)
If the control name is your button then do not do what needs to be done upon postback.
HTH
You should probably not have all this going on inside the Page_Load event. Instead, you should be handling events for each control that can cause a postback. This helps with code clarity, and ease of maintenance, not to mention better control in the first place.
Here's a nice brief blog entry I found on the subject: http://www.sitepoint.com/blogs/2007/01/21/page_load-is-evil/
Incidentally, handling events is much different in ASP.NET than in other environments, My guess, just based on the fact that you're trying to accomplish this in the Page_Load event is that you're not yet "getting" the event-driven programming model. (If I'm wrong, I apologize, I don't mean to be insulting).
If I'm right, however, once you get used to it, it's going to be a lot simpler for you than things were in the classic ASP days, for example, where you had to do things like try to figure out which button was clicked. Here's another nice article to explain this further: http://articles.sitepoint.com/article/driven-asp-net-development-c
It's hard to see this as a good idea. From the short snippet you posted, it looks like what you really need is a Validation control attached to your textbox.
Have a look at the POSTed items. You should see some sort of reference to that button in there. IIRC, if it was clicked, you will see some sort of reference in there, and if it wasn't it wouldn't be in there.
I had this same problem a while a ago and that's how I circumvented loading some stuff.

Can an ASP.NET user control determine its context or its parent .aspx file

Is it possible for a user control to determine its "context" or its parent .aspx page in some way?
Right now I have a user control that is declared on a typical .aspx page as follows:
<%# Register TagPrefix="uc1" TagName="ManageTitle" Src="../UserControls/ManageTitle.ascx" %>
The user control currently emits a textbox as follows:
<asp:textbox id="txtTitle" runat="server" MaxLength="60"
ToolTip="Describe the item with a short pithy title - most important keywords first"/>
The page_load for this .ascx file is currently like this:
Me.txtTitle.Text = SetPageTitle()
While some places in this web app need this (i.e. a textbox where end-user can type a "title"), I have other places where I want to show the "title" information in a "read-only" way. For example, rather than a textbox, I could use a label control or a textbox with Enabled="false" to prevent
data entry.
I suppose I could clone this small .ascx file and append a suffix to its name like _RO.ascx or something but I am wondering what the best approach would be.
In short, can a user control get some sort of "context" from the page that declares it or is there an altogether better way to accomplish this sort of thing? Thank you.
-- EDIT UPDATE WITH THE APPROACH SUGGESTED --------------------------
Code added to the UserControl:
Private mIsReadOnly As Boolean
Public Property IsReadOnly() As Boolean
Get
IsReadOnly = mIsReadOnly
End Get
Set(ByVal value As Boolean)
mIsReadOnly = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
'Leave the textbox alone
Else
Me.txtTitle.Text = SetPageTitle() 'This is the original code
If IsReadOnly Then
Me.txtTitle.Enabled = False
Else
Me.txtTitle.Enabled = True
End If
End If
End Sub
Code added to the parent which invokes the UC:
<uc1:ManageTitle id="ManageTitle"
IsReadOnly="True" runat="server">
</uc1:ManageTitle>
If you want to follow common patterns, expose a public property on your .ascx control (in the codebehind) that allows the containing page to set its state programmatically. You could create a State property whose value is an enum of available States (readonly, editable, etc)
This is similar to a previous question. My answer there has a link showing how this can be done, as well as an alternate approach that's more "standard"
Can I get the currently opened ASP page file name in Visual Studio.NET in a custom control?
Yes, a control can access its context, e.g. using Me.Page (I hope this is how it's done in VB.NET) to access the page.
The problem with this approach is, that it makes your controls less reusable, because they will only work in contexts which they know. Probably it would be better to switch the dependency, i.e. the page/parent control should call a GetPageTitle() method of your control and do the appropriate things with the return value.

Modify Page Head in User Control

How can I modify the head portion of a page from within an embeded user control? I know I can have the control run in the head portion of the .aspx page but I have a existing site with numerous pages that I don't want to change. One thing they all have in common is the menubar.ascx. So, I figured I could put the code there to modify the head element of the containing page, but no dice. The code I am trying to implement looks like this, however, the Page.Header is null.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim favicon As New HtmlLink
favicon.Attributes.Add("REL", "SHORTCUT ICON")
favicon.Attributes.Add("HREF", "images/bh_favicon.ico")
Page.Header.Controls.Add(favicon)
End Sub
I tried putting it in the PreRender and the Render events but same thing. The Page.Parent.Page.Header is null too. Is there a better way to do what I want to do? Utlimately I want to add a favicon to a group of pages that is different from the default favicon. Basically I have two sites on in the same code base.
Be nice, this is my first post.
TIA
You may need to make your Page Head run at server, so the usercontrol can see it.
eg:
<head runat="server">
Which I guess sort of defeats the point if this isn't already done on all your pages. Maybe a solution wide RegEx search/replace would be in order to implement this.
Thanks for your answers. I know I was asking for the least amount of work solution, however, I want to make the code easy for me to manage. I think what I am going to do is construct a master page as a template for all pages (like #devstuff suggested). Then I am going to change the existing pages, about 50 pages, to use the master page. That way if something like this pops in the future I can easily change everything in one place.
Thanks for you help!
As mentioned by #Program.X you may need a full search/replace. If you are going to do that you might want to go one step further and use a Master page, but it really depends on your time constraints and how many pages there are to modify.

asp.net: Prevent Generating Server Control Ids

The Problem
When using asp.net server controls id attributes such as the following are automatically generated.
<img id="ctl00_body_ULRepeater_ctl01_LIRepeater_ctl00_PartImg" src="img.png" />
While I'm not averse to id attributes in general, I try to stay away from using these unnecessarily verbose types of names and use concise, descriptive names.
The Question
Can I stop asp.net from generating these id attributes? They look terrible, and if I generate a lot of items with a repeater or something they actually add a good bit of page weight. How do I get rid of them?
Notes
I am using asp.net 3.0 in Visual Studio 2008.
[update]
Ok, so I can subclass (ClientID is declared overridable), but this is no fun really. I can use Literal Controls everywhere. Or I can grit my teeth and bear the painfully slow rendering of my pages with nearly nothing on them.
I believe that one of the features coming in asp.net 4.0 will be the ability to better control the IDs that are generated. For now, you are going to get the name mangling for any server generated control. This is what allows asp.net to guarantee the uniqueness of your control's ID.
You can always use straight HTML markup (do not runat=server) to avoid this issue. You would be sacrificing the ease of use for a lighter weight page though.
You can hide these id attributes completely by setting each control's Id property to null at runtime, e.g.
Private Sub repeNewsletters_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles repeNewsletters.ItemDataBound
If e.Item.DataItem Is Nothing Then
Return
End If
Dim hlDetails = DirectCast(e.Item.FindControl("hlDetails"), System.Web.UI.WebControls.HyperLink)
hlDetails.ID = Nothing
end sub
As of now ControlID's are ReadOnly properties. In the upcoming release of ASP.NET Web Forms (with .NET 4.0) this will be a settable property using a number of different methods (such as static, inherit, etc.)

Resources