Page_Load method running twice - c#

I have created a VS 2013 project using built-in asp.net Web Application Web Forms template. By putting a breakpoint in the Page_Load method of a page I can see the method is executed twice between pressing F5 and the page appearing. Why? And can I / should I stop this behaviour?
Apologies for not providing enough detail. The code is completely vanilla, untouched template code generated by VS Exp 2013 for Web.
The ASPX file is
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="mycompanyname.B1WebApp.About" %>
The ~/Site.Master has an empty Page_Load method (not sure this is relevant)
The code behind is
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Boolean Nothing;
}
}

You can avoid pageload function working on each postbacks by !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Your code here
}
}
A User control with this master page can also cause pageload execute twice...

This is part asp.net web forms, as a page posts back to itself whenever a server control is used on a page. It has been like this forever.
You need to do a check on page load:
if(!IsPostBack)
{
//Code for first time load
}
else
{
// code whenever you have a postback
}

Related

Page_Load is not executed in asp.net

I have this c# code
namespace ZumaApp
{
public partial class _Default : System.Web.UI.Page
{
ServiceReference1.QSLWebBookingSoapClient services;
public String CallerId = "";
public Int32 rowCount;
protected void Page_Load(object sender, EventArgs e)
{
CallerId = Request["CallerID"];
and in my asp I have this:
<%# Page Title="VMP Online Booking" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ZumaApp._Default" %>
My problem
The page load function is not executing.
how did I know that
First: I make a break point on the first line in the Page_Load function, but visual studio doesn't stop at the break point.
second: I make a break point at this line public String CallerId = ""; and Visual studio stops on that line, then I press step over but the page loaded without going to the Page_Load function.
I tried clean and rebuild but dones't help
try this
<%# Page Title="VMP Online Booking" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true" CodeBehind="_Default.aspx.cs" Inherits="ZumaApp._Default" %>
Try delete the .Designer.cs and recreate it by Convert to web application option.
It can be regenerated by right clicking on the aspx / ascx file and select Convert to web application option.
Some times .Designer.cs wont be refreshed by VS, and need to apply this method to get a fresh .Designer.cs file.
In the InitializeComponent function (which resides in the "Web Form Designer
generated code" region), you should have a line which says:
this.Load += new System.EventHandler(this.Page_Load);
This line of code should be automatically generated, and tells the framework
to execute the Page_Load function when the page loads. If this line is
missing, the Page_Load function won't fire. Adding this line should solve
your problem.
Reference: Page_Load Not Firing?

How can I change my page's Master Page at runtime?

There is a requirement in one of my project, where I need to change Master Page during run time.
I mean I need to apply check and on the basis of that check particular master page can be called to my native aspx page.
Please help me out for same.
Thanks in advance :)
For example:
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
Apply your conditionals as required. From here.
Yes. Set the MasterPageFile property only during the PreInit page event—that is, before the runtime begins working on the request (since the rendering of the page with the master page occurs prior to the Init event)
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "simple2.master";
}
If you try to set the MasterPageFile property in Init or Load event handlers, an exception is raised.
Yes it is possible, Implement like below
Dynamically Loading Master Pages in ASP.NET 2.0
To acheive this we need to write code in Page_PreInit before page gets render.
Put below code into your code behind:
if (Session["userType"] == "Admin") //check the user type
this.Page.MasterPageFile = "~/Admin.master";
else
this.Page.MasterPageFile = "~/User.master";
Hope this helps.

Caching issue: ascx/usercontrol's programmatic Page.Title ignored during cached load of page

The problem is: When a user vists Default.aspx, the page loads the cached version of the Blog.ascx content (because it has hit the same page again within 600 seconds), the Page.Title code is not executed therefore the title remains empty instead of having <title>Title of Blog Post</title> like when it freshly loads the page the first time.
My asp.net website has Blog.ascx to handle loading the content of an individual blog post. Default.aspx contains the reference to and uses the Blog.ascx
The Blog.ascx page has custom caching:
<%# OutputCache Duration="600" VaryByParam="None" VaryByCustom="Url" %>
The custom caching, located at global.asax.cs is:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
switch (custom.ToUpper())
{
case "URL":
return context.Request.Url.ToString().ToLower().Trim();
default:
throw new NotImplementedException();
}
}
The Blog.ascx.cs Page_Load event handles the programmatic tag's value/content
protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "Title of Blog Post";
}
Any suggestions?
Have you considered using UserControls?
If you created a UserControl for the content of you page, you could move the OutputCache declaration to the control, thus freeing up the Page_Load event to set the Page title every visit.

ASP.NET not calling code behind even in debug

as it says, when I run my application in debug the code-behind isn't being called.
I had this problem to start with and managed to get around it by abandoning the page I was working on and starting a completely new one.
However it seems this one has now broken also!
Basically it just opens showing the unaltered HTML without running any of the C# code and without hitting any breakpoints.
It builds ok but I haven't tried deploying it yet as I don't have a server available at the moment.
This is my code behind from index.aspx.cs:
namespace PAPS
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = User.Identity.Name;
// check security
Security security = new Security(username);
divUsername.InnerText = username;
security = null;
}
}
}
The page declaration from index.aspx is as follows:
<%# Page Language="C#" AutoEventWireup="false" EnableSessionState="True" EnableViewState="false" CodeBehind="index.aspx.cs" Inherits="PAPS.index" %>
Anyone have any useful suggestions?
Thanks
You have
AutoEventWireup = false
Unless you're handling the events yourself, try setting that to true.

Masterpage check session issue

I'm fixing my friend's codes. And I have a problem with session value in masterpage.
I'm checking session is null or empty in masterpage and if it's null go to login page.
But other pages that created by masterpage never works.
if (Session["user"] != null && Session["user"] != "")
{ }
else
{
Response.Redirect("/Account/Login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
I tried with Session["user"].ToString() but same result.
And the otherpages have a other controls via this session so it always give error if you are not login.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
MaintainScrollPositionOnPostback="true" CodeFile="document.aspx.cs" Inherits="document" %>
Based on this:
But session control in back.master's page_load fire after default.aspx page_load so it gives me error the "session is null"
The root problem here is simple... You need to fully understand the ASP.Net page life-cycle
Take a quick look:
Basically your following assumption is wrong:
Then i create normal aspx page which name is default.aspx and is derived by back.master
From MSDN:
Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events
Sadly an ASP.Net does not derive from a Master Page Why? because a Master Page is treated as a control so what really happens is that the master page is a child control of the Page
Alternatives:
Since you are checking if the user is authenticates, it would be better if you rely on the ASP.Net authentication and authorization API
Workarounds (if you insist to use your own authentication mechanism):
(Best recommendation) Create a custom HttpModule and check the Session object there. I think the event that best fits your needs is the: Application_AuthenticateRequest. This is a full list of events you can choose from: (BTW there's no need to create a new HttpModule, you could subscribe to events using the Global.asax file of your web application, use an HttpModule only if you would like to encapsulate the logic to reuse it)
Application_BeginRequest.
Application_AuthenticateRequest.
Application_PostAuthenticateRequest.
Application_DefaultAuthentication.
Application_AuthorizeRequest.
Application_PostAuthorizeRequest.
Application_ResolveRequestCache.
Application_PostResolveRequestCache.
Application_MapRequestHandler. Fired only when the server is running IIS 7 in Integrated Mode and at least >Net Framework 3.0
Application_PostMapRequestHandler.
Application_AcquireRequestState.
Application_PostAcquireRequestState.
Application_PreRequestHandlerExecute.
The page event handler is executed. (refer to the page life cycle)
Application_PostRequestHandlerExecute.
Application_ReleaseRequestState.
Application_PostReleaseRequestState
Application_UpdateRequestCache.
Application_PostUpdateRequestCache
Application_LogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
Application_PostLogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
Application_EndRequest.
For more info:
ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0
ASP.NET Application Life Cycle Overview for IIS 7.0
Create a generic page inheriting from Page and place the check code there in the PreLoad or Load event, both events would work and finally inherit all your pages from this page
(Not recommended) If you want to encapsulate the check inside the Master Page, you could use the Init event
IIS has standard methods for authentication and authorization.
If you want to restrict access to certain areas of your website if the user isn't logged in, then there are mechanisms in the configuration that allow for that:
In your web.config you can add:
<location path="LoginRequiredDir">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
This will automatically take users to the login page if they are not logged in.
Fix: It will solve your issue.
protected void Page_Init(object sender, EventArgs e)
{
if (Session["master"] != null)
{ }
else
{
Response.Redirect("login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
}
I also had similar issue faced. I used true to the Response.Redirect method so that the rest of load should gets terminated. Ref. I checked the session value in Page_Init of the master page as below.
public partial class Dashboard : System.Web.UI.MasterPage
{
protected void Page_Init(object sender, EventArgs e)
{
if (Session["RoleId"] == null || Session["RoleId"].ToString() == "")
{
Response.Redirect("/account", true);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
setUserInfo();
}
}
}
Hope it helps.
You define the above code Page_Load method in following way:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null && Session["user"].ToString() != "")
{
//do code here
}
else
{
Response.Redirect("/Account/Login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
}

Categories

Resources