ASP.NET not calling code behind even in debug - c#

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.

Related

Weird Error on Visual Studio - "you could use the navigation bar to switch context"

I have been trying to link a a web form to be a able to access a variable in the master page. I did this before it worked. But now when I do it I get an error.
The code in Site.Master
<%# Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %>
The code in Site.Master.cs
public partial class Site : System.Web.UI.MasterPage
{
public string hi = "";
protected void Page_Load(object sender, EventArgs e)
{
}
}
The code in WebForm1.aspx:
<%# Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="WebForm1.aspx.cs" Inherits="WebForm1" %>
<%# MasterType VirtualPath="~/Site.master" %>
The Code in WebForm1.aspx.cs
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Master.hi="new"
}
}
When I hover over the hi, I get this message
Error in Visual Studio - "You can use navigation bar to switch contexts
Here is another image
Screenshot
If you guys could help me it will really be great
I had this same problem in an MVC application so the WebForm-CodeFile-CodeBehind suggestion didn't really apply.
However, I realized the new classes that I created had their "Build Action" set to "Content". Once I changed this to "Compile", everything started working again.
In your WebForm1.aspx, try changing CodeFile to CodeBehind. That's what worked for me.
Try adding manual the ID of the form into the designer "yourname".aspx.designer.cs, in your case I guess it should be WebForm1.aspx.designer.cs.
You'll see a reference line for every id you have. You need to add a line like this -> "protected global::System.Web.UI.HtmlControls.HtmlForm hi" if you added the form like normal html
or -> "protected global::System.Web.UI.FormView hi" if you added as an aspx element

Button Click To Send To New Page

I have tried both Response.Redirect and Server.Transfer to take me to a new page on button click, but every time my page just refreshes and I am never redirected to the new page. I have verified the page exists in my project and even copied/pasted the name of the page into my syntax to make sure no weird spaces or anything, but I NEVER get redirected
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
filldropdowns();
}
}
protected void btn1_OnClick(object sender, EventArgs e)
{
Response.Redirect("page2.aspx");
Server.Transfer("page2.aspx");
}
<div id="btn11" algn="center">
<asp:Button ID="ClickBtn1" runat="server" Text="Push Me" OnClick="btn1_OnClick" OnClientClick="return ValidateData();" />
</div>
<script type="text/javascript">
function ValidateData() {
var name;
name = document.getElementById("txtName").value;
if (name == '' || name.trim() == '') {
alert("Please enter a valid name");
return false;
}
}
</script>
EDIT
using the ~/ will allow a redirect but it throws the below error. The page does exist!
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /page2.aspx
EDIT 2
This is the markup for my page2 if that matters
<%# Page Language="C#" AutoEventWireup="true" CodeFile="page2.aspx.cs" Inherits="page2" %>
And if I use localhost in my redirect it loads no problem, but I am ready to push this out into the interweavings of the web and can not use localhost anymore. What should I change this to?
http://localhost:1444/TestProject/page2.aspx
EDIT 3
If it helps (or matters) the full location to the .aspx page that I want to redirect to is this:
C:\Users\Habib\Documents\Visual Studio 2015\Projects\Test\TestProject\Page2.aspx
You have shown syntax that is known to work whether it be means of Response.Redirect() or Server.Transfer() those methods are tried and true to be successful. If when you step through your code it hits your break point for the re-direct, then show us what you have in your Page_Load() for page2.aspx.
And we can help further diagnose and/or troubleshoot from that.

Page_Load method running twice

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
}

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?

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