How to add html using Razor templates from database to views at runtime

江枫思渺然 提交于 2021-01-07 01:37:08

问题


In ASP.NET Core 5 MVC shopping cart application users can change shipping price calculation, discount options and other such things at runtime.

They are editing Razor templates in text editor outside Visual Studio and outside application using non .NET application. Those templates are saved in database.

Views contain hook calls:

@inherit ViewPageBase<object>
<head>
@Hook(ElementName.BeforeHeadContent)
...
<body>
@Hook(ElementName.Body)
...
@Hook(ElementName.Footer)
...
</body>

Hook method is implemented in view base class:

public abstract class ViewPageBase<TPageModel> : RazorPage<TPageModel>

  public IHtmlContent Hook(ElementName elementName)
  {
      StringBuilder sb = new StringBuilder();

      foreach (var l in GetDynamicRazorTemplatesFromDatabase(elementName))
      {
         string parsed = RazorRenderer.CompileAndRender<TPageModel>(l.Webcontent, Model);
         sb.AppendLine(parsed);
      }

      return new HtmlString(sb.ToString());
  }

During view creation those view fragments are compiled, executed and result html is inserted to views in raw form.

I wast told that accessing database from views (GetDynamicRazorTemplatesFromDatabase) method is poor design.

How to implement this better in ASP.NET Core 5 MVC?

来源:https://stackoverflow.com/questions/65537305/how-to-add-html-using-razor-templates-from-database-to-views-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!