首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET Label 換行顯示完整解決方案:WebForms、MVC、WinForms 跨平台處理

     編輯:ASP.NET 基礎

核心問題

HTML 忽略換行字元 (`\r\n`, `\n`),需轉換為 `
` 標籤才能在瀏覽器正確換行。`Label` 控制項輸出 ``,預設不解析 HTML,需配合 `Encode="false"` 或前端 CSS 處理。

ASP.NET WebForms 解決方案

方案一:後台替換 (傳統、相容性佳)


// C# 後台
protected void btnSubmit_Click(object sender, EventArgs e) {
    // TextBox.TextMode="MultiLine" 時,換行為 \r\n
    lblResult.Text = txtInput.Text.Replace("\r\n", "
").Replace("\n", "
"); }





方案二:CSS 白空間處理 (現代、無需替換)






後台直接指派:lblResult.Text = txtInput.Text; — 瀏覽器自動依 CSS 渲染換行。

方案三:VB.NET 專屬 (舊專案相容)


' 儲存時:將 vbCrLf 替換為特殊標記 (如 |)
Dim savedText As String = txtInput.Text.Replace(vbCrLf, "|")

' 讀取時:還原為 
lblResult.Text = savedText.Replace("|", "
")

ASP.NET Core MVC / Razor Pages

模型繫結與顯示


// Model
public class Post {
    public string Content { get; set; }
}

// Controller
public IActionResult Create(Post model) {
    _db.Posts.Add(model);
    _db.SaveChanges();
    return RedirectToAction("Detail", new { id = model.Id });
}

Razor 視圖三種換行渲染方式



@Model.Content
@Html.Raw(Model.Content.Replace("\r\n", "
").Replace("\n", "
"))
@Html.PreserveNewlines(Model.Content)

HtmlHelper 擴充方法


public static class HtmlExtensions {
    public static IHtmlContent PreserveNewlines(this IHtmlHelper helper, string text) {
        if (string.IsNullOrEmpty(text)) return HtmlString.Empty;
        var encoded = System.Net.WebUtility.HtmlEncode(text); // 先編碼防 XSS
        var withBr = encoded.Replace("\r\n", "
").Replace("\n", "
"); return new HtmlString(withBr); } }

WinForms / WPF 桌面應用

平台控制項換行處理
WinFormsTextBox (Multiline=true)直接指派 textBox.Text = "Line1\r\nLine2" 自動換行
WinFormsLabel需設 AutoSize=false、MaximumSize 寬度,文字含 `\n` 即可換行
WPFTextBlockText="Line1 Line2" 或 `` XAML 標籤
WPFTextBoxAcceptsReturn="True" TextWrapping="Wrap"

長文字自動換行 (防止撐破版面)


/* 通用 CSS - 針對 Label、Div、Span 等行內/區塊元素 */
.text-auto-wrap {
    white-space: pre-wrap;       /* 保留原始換行 */
    word-wrap: break-word;       /* 斷詞換行 (舊屬性) */
    overflow-wrap: break-word;   /* 現代標準屬性 */
    word-break: break-all;       /* CJK 強制逐字斷行 */
    max-width: 100%;             /* 限制最大寬度 */
    display: block;              /* Label 預設 inline,需改 block */
}

安全性提醒:防 XSS

若使用者輸入含 HTML/Script,直接 `` 或 `@Html.Raw` 會導致 XSS。


// 安全流程:先 HtmlEncode,再替換換行
string safe = System.Net.WebUtility.HtmlEncode(userInput);
string withBr = safe.Replace("\r\n", "
").Replace("\n", "
"); lblResult.Text = withBr; // Encode="false" 此時安全,因已編碼

快速選擇指南

場景推薦方案關鍵點
WebForms 簡單表單方案一 (後台 Replace + Encode=false)相容舊瀏覽器、邏輯明確
WebForms 現代專案方案二 (CSS white-space: pre-wrap)無後台處理、支援長文字自動換行
MVC/Razor 新專案CSS 方式 + HtmlHelper 擴充關注點分離、防 XSS 內建
WinForms/WPF控制項原生支援無需特殊處理
需儲存原始換行至 DB直接存 `\r\n`,前端決定渲染方式資料純淨、前端彈性
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved