使用MVC渲染带有嵌入式Razor变量的动态HTML [英] Render dynamic HTML with embedded Razor variables using MVC

查看:308
本文介绍了使用MVC渲染带有嵌入式Razor变量的动态HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些已编码的HTML,其中存储了数千个不同的Razor变量,我已经存储了它们,它们需要从数据库中检索.我希望能够在MVC/剃刀视图中呈现此图像.

I have some encoded Html which have any number of 1000s of different Razor variables embedded within it that I have stored and need to retrieve from the database. I want to be able to render this in a MVC/razor view.

仅是保存在数据库中的html的一个简单示例(可能更复杂):

Just one simple example of the html saved on the database (it can be more complex):

"<span>Your page is @Config.PageColour and you have page size of @Config.PageSize</span>"

MessageController.cs

public ActionResult ShowMessage()
{
    var htmlToDisplay = _messageDAL.getHtmlMessage();
    var messageVm = new MessageVm
    {
        DisplayMessage = htmlToDisplay;
    };

    return View("Index.cshtml", "", messageVm);
}

Index.cshtml

<html>
    @Html.Raw(@model.DisplayMessage)
</html>

结果

当我运行此代码时,呈现的页面如下所示:

When I run this the rendered page looks like this:

您的页面为 @ Config.PageColour ,页面大小为 @ Config.PageSize

但是我希望它用html块解释Razor变量的值,并且应该像这样:

But I want it to interpret the value of the Razor variable with the html block and should look like this:

您的页面为蓝色,并且页面大小为 A4

Your page is Blue and you have page size of A4

真的坚持在这里,所以任何帮助将不胜感激!

Really stuck on this so any help would be appreciated!

推荐答案

使用此行.希望对您有所帮助.

Use this line. I hope this may help.

@Html.Raw(System.Web.HttpUtility.HtmlDecode(@model.DisplayMessage))

编辑1

您可以使用以下提到的任何Razor编译器

You can use any Razor Compiler like the one mentioned below

RazorEngine :

string result = RazorEngine.Razor.Parse(@model.DisplayMessage, new { Name = "Name" });

RazorEngine不支持任何Mvc帮助器,例如Html和Url.由于这些库应该存在于Mvc之外,因此需要更多的工作才能与这些帮助程序一起使用.**

RazorEngine does not support any of the Mvc helpers such as Html and Url. Since these libraries are supposed to exist outside of Mvc and thus require more work to get them to work with those helpers.**

编辑2

您可以使用Razor编译器,该编译器允许您使用称为RazorEngine的HTML模板,该模板可在 https://中找到. github.com/Antaris/RazorEngine

You can use a Razor compiler that allows you to use HTML templates called RazorEngine which can be found at https://github.com/Antaris/RazorEngine

使用 Package Manager控制台命令从 Visual Studio :

Install-Package RazorEngine

安装后,我如下更改了控制器:

After installation I changed my controller as follows:

MessageController.cs

public ActionResult ShowMessage()
{
    var htmlTemplate = _messageDAL.getHtmlMessage();

    var htmlToDisplay = Engine.Razor.RunCompile(htmlTemplate , "messageTemplateKey", null, new { Name = "some model data" });

    var messageVm = new MessageVm
    {
        DisplayMessage = htmlToDisplay;
    };

    return View("Index.cshtml", "", messageVm);
}

这篇关于使用MVC渲染带有嵌入式Razor变量的动态HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆