c# – Develop standard template Razor – ASPNET MVC

Question:

I'm with an ASPNET MVC5 project using C# that, by project definition, it was agreed that the layout of the structure of the pages would be stored in the Database.

Inside my _ViewStart my _Layouts.cshtml would be referenced which would be the common content of the pages. So far so good, the problem is that the content that would be the structure of the site would be fetched from the database, with all HTML and Razor elements, and rendered on screen. For plain HTML (without any Razor) this would work fine with some of the following alternatives (view code _layouts.cshtml where HTML Content would be fetched from the database and returned by the controller):

  • @ViewBag.HTMLContent or @Html.Raw(ViewBag.HTMLContent.ToString())
  • or even creating a Helper and referencing in the view: @MeuHelper.Template(ViewBag.ConteudoHTML.ToString())

The problem is that I store in the database the structure that already contains my references to Models, ViewBag, Helpers, etc. When rendering the browser doesn't recognize Razor elements (besides, in my View the compiler doesn't run without the explicit RenderBody() there, even though I've already inserted it along with the bank record).

I researched here and saw a possible solution using RazorEngine, but in my tests here it is not working at all for more complex HTML's (involving Custom Helpers for example).

Could someone help me with any feature ideas to implement?

Example of contents: – HTML stored in the database

<!DOCTYPE html>
<html lang="pt-br" xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br">
<head>
    <meta charset="utf-8" />    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="@ViewBag.MetaDescription" />
    <meta name="keywords" content="@ViewBag.MetaKeywords" />   
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>@ViewBag.Title</title>                
    <!--[if IE]><link href="~/css/images/favicon.ico"><![endif]-->
    <link href="@Url.Content("~/css/images/favicon.png")" />
    <link type="text/css" href="@Url.Content("~/css/bootstrap.min.css")" />
    @RenderSection("Css", required: false)
</head>

<body>
    @RenderBody()
</body>
</html>

– Code not controler

public virtual ActionResult Index()    
{
    ViewBag.ConteudoHTML = "";//HTML vindo do banco, html acima
    ViewBag.Title = "Meu título";
    ViewBag.MetaDescription = "Description";
    ViewBag.MetaKeywords = "Keywords";

    return View();
}

— View code (_Layouts.cshtml)

@ViewBag.ConteudoHTML

NOTE: as I've tried to implement this in different ways, there's no way to put all the solutions I've tried, but they don't differ much from this one.

Answer:

I managed to solve it using the superscript VirtualPathProvider.

The contribution of TobyMosque through the link http://www.umbraworks.net/bl0g/rebuildall/2009/11/17/ASP_NET_MVC_and_virtual_views was useful.

Scroll to Top