HTML 忽略換行字元 (`\r\n`, `\n`),需轉換為 `
` 標籤才能在瀏覽器正確換行。`Label` 控制項輸出 ``,預設不解析 HTML,需配合 `Encode="false"` 或前端 CSS 處理。
// C# 後台
protected void btnSubmit_Click(object sender, EventArgs e) {
// TextBox.TextMode="MultiLine" 時,換行為 \r\n
lblResult.Text = txtInput.Text.Replace("\r\n", "
").Replace("\n", "
");
}
後台直接指派:lblResult.Text = txtInput.Text; — 瀏覽器自動依 CSS 渲染換行。
' 儲存時:將 vbCrLf 替換為特殊標記 (如 |)
Dim savedText As String = txtInput.Text.Replace(vbCrLf, "|")
' 讀取時:還原為
lblResult.Text = savedText.Replace("|", "
")
// 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 });
}
@Model.Content
@Html.Raw(Model.Content.Replace("\r\n", "
").Replace("\n", "
"))
@Html.PreserveNewlines(Model.Content)
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 | TextBox (Multiline=true) | 直接指派 textBox.Text = "Line1\r\nLine2" 自動換行 |
| WinForms | Label | 需設 AutoSize=false、MaximumSize 寬度,文字含 `\n` 即可換行 |
| WPF | TextBlock | Text="Line1
Line2" 或 ` |
| WPF | TextBox | AcceptsReturn="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 */
}
若使用者輸入含 HTML/Script,直接 `
// 安全流程:先 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`,前端決定渲染方式 | 資料純淨、前端彈性 |