-
ASP.NET Code Behind C#
I've learning ASP.NET using c# at present. I've got an example of using code behind but its not working can anyone point out why its not working?
myCodeBehind.cs:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public class myCodeBehind: Page {
protected Label lblMessage;
protected void Button_Click(Object sender , EventArgs e) {
lblMessage.Text="Hello World!!";
}
}
Presentation.aspx
<%@ Page codebehind="myCodeBehind.cs" Inherits="myCodeBehind" Language="C#" %>
<html>
<head><title>Presentation.aspx</title></head>
<body>
<form Runat="Server">
<asp:Button
Text="Click Here!"
OnClick="Button_Click"
Runat="Server" />
<p>
<asp:Label
ID="lblMessage"
Runat="Server" />
</form>
</body>
</html>
There is a parser error - cannot find myCodeBehind. So the first line of the aspx file is at fault - but what is wrong?
Any ideas?
DJ
-
Code behind is compiled into a .dll, usually into c:\inetpub\wwwroot\ProjectName\bin directory, assuming that c:\inetpub is the installation directory for IIS. If the worker process (aspnet_wp.exe on Win2k & XP, w3wp.exe on Win 2003) can't find the compiled code, you'll get the parser error.
Just rebuild your application & it should sort itself out, or just hit F5 in VS.Net.
-
I'm using Web Matrix so I don't have all the additional features of VS.NET.
In the book I'm currently reading it says that I don't need to compile the code behind page if I used the code as above - it will compile automatically.
I might try setting a path in Windows to csc.exe to see if thats the problem.
DJ
-
No, you do have to compile - boiled down, there isn't a .Net .dll until you do.
You might be thinking about JIT - Just In Time compiling. Something completely different - this is compiling to native code at the first request for a page held within your dll.
If your code was inline (like classic ASP), then you wouldn't have to compile, it would be interpreted.
-
Ok heres a direct quote from ASP.NET Unleashed...
Notice you don't even have to compile the code-behind file. The Visual Basic class contained in the code-behind file is compiled automatically when you request the Presentation.aspx page.
Now I know I've used C# instead of VB.NET but I've used the example on a CD supplied by the book. Are you absolutely positive you have to compile the code-behind file because its pretty black and white in the book.
DJ
-
Compile the app & run it. If it works, then I'm wrong :)
-
Ok I've finally found the solution.
If I change:
<%@ Page codebehind="myCodeBehind.cs" Inherits="myCodeBehind" Language="C#" %>
to:
<%@ Page src="myCodeBehind.cs" Inherits="myCodeBehind" Language="C#" %>
Then I don't need to compile myCodeBehind.cs - it does it on the fly.
Bloody mistakes in books - they drive me round the bend!
DJ
-
Didn't know one could do that.
Would seem that we were both right :)