【发布时间】:2020-12-02 00:09:54
【问题描述】:
我目前正在开发一个 asp.net MVC Web 应用程序,我必须在其中生成或多或少复杂的 HTML 结构,然后将其插入 Razor 页面。目前我生成带有字符串连接的 HTML,然后将字符串添加到我的控制器中的 ViewBag 中,如下所示:
public class SomeController : Controller
{
public IActionResult Index()
{
string htmlString = "<div id=\"example-div\">Some more Stuff</div>" + "Some more HTML strings";
Viewbag.htmlString = htmlString;
return View();
}
}
然后我访问该字符串并将其呈现为我的 Razor 页面中的 HTML,如下所示:
@Html.Raw(ViewBag.htmlString)
但这不是最佳做法。有没有更好的方法在我的控制器中实际生成一个 HTML DOM 元素,然后像模板一样将该元素加载到剃须刀页面中?如果有怎么办?
谢谢
【问题讨论】:
-
如果可能,您可以创建自定义 Html Helper 并返回 MVChtmlString
标签: c# html asp.net-mvc razor-pages