ASP   «Prev  Next»


Lesson 8 Writing Output in ASP.NET
Objective Techniques for writing variables, text, and HTML to the browser in ASP.NET

Sending Output to the Browser in ASP.NET

In the early days of ASP and classic ASP.NET Web Forms, developers commonly used Response.Write() to send text, variables, and HTML directly to the browser. While this method still works, modern ASP.NET frameworks offer cleaner, safer, and more flexible ways to output data - depending on whether you're using ASP.NET Core, MVC, or legacy Web Forms.

ASP.NET Core (Modern and Recommended)

In ASP.NET Core - including MVC, Razor Pages, and Minimal APIs - direct use of Response.Write is no longer standard. Instead, you write asynchronously to the response body or return structured content results.

1. Returning Content from a Controller or Razor Page

The most common and readable method is to return a ContentResult, which specifies the text and its MIME type (such as text/html).


using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult ShowHtml()
    {
        string message = "This is a bold message.";
        string html = $"<h1>Hello from ASP.NET Core</h1><p>{message}</p>";
        return Content(html, "text/html");
    }
}

2. Writing Directly with HttpResponse.WriteAsync

For middleware or lower-level control, you can write directly to the HTTP response stream.



// In a Controller, Razor Page, or Minimal API endpoint
public async Task WriteDirectly()
{
    string name = "world";
    string html = $"<h1>Hello, {name}!</h1>";

    Response.ContentType = "text/html";
    await Response.WriteAsync(html);
}

ASP.NET MVC 5 and Razor (Legacy but Common)

ASP.NET MVC uses Razor syntax in .cshtml files to combine C# code and HTML markup. Razor automatically encodes output to prevent cross-site scripting (XSS).

1. Writing Variables (HTML Encoded)


// In a Razor view (.cshtml)
@{
    string myVariable = "<script>alert('oops');</script>";
}
<p>@myVariable</p>

This will display the literal text rather than executing a script, keeping users safe.

2. Writing Raw HTML

When you need to output raw HTML intentionally (for example, formatting from a CMS), you can use @Html.Raw(). Use this with caution - never render untrusted user input.


// In a Razor view (.cshtml)
@{
    string myHtml = "This is <strong>bold</strong> text.";
}
<div>@Html.Raw(myHtml)</div>

The browser will render the bold text as intended.

ASP.NET Web Forms (Classic)

The original Response.Write() method still works in ASP.NET Web Forms, but it's not recommended for modern applications. It directly writes to the output stream, bypassing the page lifecycle.


Code-Behind Example


protected void Page_Load(object sender, EventArgs e)
{
    string user = "Admin";
    Response.Write("Hello, " + user);
    Response.Write("<h1>Welcome to Web Forms</h1>");
    Response.Write("<p>Generated dynamically at runtime.</p>");
}

Inline Output with <%= %>

You can also insert variables directly into your .aspx markup using a "code nugget."


<body>
    <form id="form1" runat="server">
        <div>
            Your message: <%= MyPublicVariable %>
        </div>
    </form>
</body>

// In Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
    public string MyPublicVariable = "This is <strong>my message</strong>.";
}

Summary

While Response.Write() remains part of ASP.NET’s legacy, developers should prefer structured, framework-native methods in modern applications:

Adopting these modern patterns ensures that your applications are secure, maintainable, and aligned with current ASP.NET development standards.


SEMrush Software