In ASP.NET Web Forms, put most C# in the page’s code-behind file and connect it to markup with server controls and events. For a small, render-time value, call a page method with <%= ... %>. A single-file .aspx page can also contain server-side C# inside <script runat="server">.
Use code-behind for normal page behavior
Code-behind keeps presentation and server logic separate. The @Page directive identifies the C# class, while an event attribute such as OnClick connects a server control to a method.
Default.aspx
<%@ Page Language="C#" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Run C#" OnClick="Button1_Click" />
<asp:Label ID="Result" runat="server" />
</form>
Default.aspx.cs
using System;
using System.Web.UI;
namespace Demo
{
public partial class Default : Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Result.Text = "C# ran on the server.";
}
}
}
When the button is clicked, Web Forms creates the event connection and invokes Button1_Click during the page lifecycle. The usual handler signature is protected void MethodName(object sender, EventArgs e). Other server events, such as Page_Load, use the same event-driven model.
Put C# directly in a single .aspx file
For small legacy pages or quick examples, declare the language on the page and add a server script block. The runat="server" attribute is what makes the block execute on the server.
#1 Best Overall
<%@ Page Language="C#" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Result.Text = "C# ran on the server.";
}
</script>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Run C#" OnClick="Button1_Click" />
<asp:Label ID="Result" runat="server" />
</form>
Inline server code is supported, but substantial logic becomes difficult to read, test and maintain when it is mixed with markup. Move reusable or complex behavior into code-behind or another class.
Display a C# method’s return value while rendering
Use an embedded expression when you need to insert one simple value into the generated HTML. The expression runs during the page’s render phase and writes the returned value into the response.
Rank #2
<%@ Page Language="C#" %>
<script runat="server">
protected string GetGreeting()
{
return "Hello from server C#";
}
</script>
<span><%= GetGreeting() %></span>
<%= ... %> is intended for output, not for handling a postback. Use a server-control event when the operation needs request data, validation, authorization, state management or other lifecycle processing.
Choose the right calling pattern
| Need | Pattern | Why |
|---|---|---|
| Respond to a button or other user action | Server control event, such as OnClick, mapped to code-behind |
Runs at the appropriate point in the page lifecycle and keeps logic maintainable. |
| Share page behavior or business logic | Code-behind method or a separate C# class | Separates compiled code from presentation and allows reuse. |
| Insert one simple value during rendering | <%= Method() %> |
Writes a method’s return value directly into the response. |
| Try a short legacy snippet | <% ... %> or <script runat="server"> |
Useful for small pages, but harder to maintain as logic grows. |
Make the page directive and class agree
For code-behind to compile and load, the page directive and C# class must describe the same page:
Language="C#"identifies the server language.CodeBehind="Default.aspx.cs"points to the code-behind file in projects that compile it separately.Inherits="Demo.Default"must match the namespace and class name in the C# file.- The class should inherit from
System.Web.UI.Pageand normally be declared as a partial class.
If these names differ, the page may fail to compile or report that the handler or control does not exist.
Fix common “C# did not run” problems
The control is not treated as a server control
Add runat="server" to the control. Without it, ASP.NET treats the element as ordinary markup, so no server-side ID or event is available.
Rank #4
The button handler never fires
- Ensure the markup contains
OnClick="Button1_Click". - Check that the C# method is spelled exactly
Button1_Click; matching is case-sensitive in practice because the name must resolve to the page member. - Use the expected signature:
protected void Button1_Click(object sender, EventArgs e). - Confirm the page’s
Inheritsvalue points to the class containing the handler. - Make sure the button is inside a form with
runat="server".
The expression prints nothing or causes an error
Verify that the method is a member of the current page class, returns a value compatible with the output, and is written as <%= GetValue() %>. This syntax is for markup output; it is not valid in server-control attribute values.
State or validation is wrong
Do not replace lifecycle handlers with a render-time expression. Put postback processing, validation, authorization and state-dependent work in events such as a button handler or Page_Load, where Web Forms supplies the request lifecycle.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsBest Value
Inline statements versus output expressions
ASP.NET Web Forms also supports inline statement blocks such as <% ... %>. They can execute C# while the page is being processed, whereas <%= ... %> specifically evaluates an expression and emits its result. Both are appropriate only for limited presentation code; event handlers and code-behind are the safer default for application behavior.
The Bottom Line
Use code-behind plus server-control events for real page behavior, <script runat="server"> for a small single-file page, and <%= Method() %> only to render a simple value.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




