在 MVC 中重用 ASP.NET WebForm (.aspx) 與使用者控制項 (.ascx) 的核心技巧:HtmlTextWriter 將控制項渲染為字串,Controller 回傳 ContentResult。
AspNets 目錄,新增 WebForm1.aspx 與 WebUserControl1.ascxPage.ParseControl 或建立頁面實例,以 HtmlTextWriter + StringWriter 捕獲輸出Content(htmlString, "text/html")public ActionResult AspxTest() {
var page = new WebForm1();
var writer = new StringWriter();
var htmlWriter = new HtmlTextWriter(writer);
page.RenderControl(htmlWriter);
return Content(writer.ToString());
}
此法讓 MVC 專案漸進式遷移舊 WebForm 元件,無需立即重寫所有頁面。