DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

How to Call C# Code Within an ASPX Page

Connect ASPX markup to C# with code-behind events, inline server scripts or a render-time expression. See working examples and troubleshoot handlers that do not fire.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<%@ 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.

<%@ 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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • 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.Page and 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.

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 Inherits value 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.