简体   繁体   English

生成 HTML DOM 元素并将其插入 Razor 页面

[英]Generating HTML DOM Element and inserting it into a Razor Page

I currently am working on a asp.net MVC web application in which I have to generate a more or less complex HTML structure and then insert it into a Razor Page. I currently am working on a asp.net MVC web application in which I have to generate a more or less complex HTML structure and then insert it into a Razor Page. Currently I generate the HTML with string concatenation and then add the string to the ViewBag in my controller, like this:目前,我生成带有字符串连接的 HTML,然后将字符串添加到我的 controller 中的 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();
    }
}

And then I access and render that String into HTML inside of my Razor Page like this:然后我访问该字符串并将其渲染到我的 Razor 页面内的 HTML 中,如下所示:

@Html.Raw(ViewBag.htmlString)

But this can't be best practice.但这不是最佳实践。 Is there a better way to actually generate a HTML DOM element inside my controller and then load that element into the razor page like a template?有没有更好的方法在我的 controller 中实际生成 HTML DOM 元素,然后像模板一样将该元素加载到 razor 页面中? If so how?如果有怎么办?

Thanks谢谢

Here you can create your own custom extension helper.在这里,您可以创建自己的自定义扩展助手。

  • Create static class创建 static class

  • Create a static method创建 static 方法

  • Register namespace in the web.config view folder for global access in all pages在 web.config 视图文件夹中注册命名空间,以便在所有页面中进行全局访问

  1. Create one class创建一个 class
public static class HtmlHelpers   
{   
     public static MvcHtmlString RenderTemplate(this HtmlHelper helper, string moreHtml=default(string))   
     {   
        MvcHtmlString ohtml = null;
        StringBuilder builder=new StringBuilder();
        builder.Append("<div id=\"example-div\">");
        builder.Append("Some more Stuff");
        builder.Append(moreHtml);
        builder.Append("</div>");
        ohtml =new MvcHtmlString(builder.ToString());
        
        return ohtml;
     }  
 } 
  1. Register your class namespace in the web.config inside namespaces attributenamespaces属性内的 web.config 中注册您的 class 命名空间
<add namespace="YOURNAMESPACE"/>
  1. Open any cshtml page and try to type this keyword.打开任何 cshtml 页面并尝试输入此关键字。
@Html.RenderTemplate() // Default template
@Html.RenderTemplate("<span>More stuff</span>") // Customized template

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM