在HTML字符串内渲染ViewComponent [英] Render ViewComponent inside html string

查看:80
本文介绍了在HTML字符串内渲染ViewComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为MyComponent的ViewComponent.

Lets say I have a ViewComponent named MyComponent.

从ASP.NET Core 1.1开始,我可以通过在剃刀视图.cshtml页面中编写此ViewComponent来呈现此ViewComponent:

As of ASP.NET Core 1.1 I can render this ViewComponent by writing this inside a razor view .cshtml page:

 <vc:my-component></vc:my-component>

我想做这样的事情:

@{string myHtml = "<vc:my-component></vc:my-component>";}

@(new HtmlString(myHtml))

我通过这样做安装并尝试了RazorEngine,但这没有用:

I installed and tried RazorEngine by doing this, but this did not work:

string template = "<vc:my-component></vc:my-component>";
var result = Engine.Razor.RunCompile(template, "messageTemplateKey", null, new { Name = "some model data" });
ViewBag.result = result;

然后在.chtml文件中:

then in the .chtml file:

 @(new HtmlString(ViewBag.result))

此问题的背景是,我已经创建了一个ViewComponent,其中包含一些有关如何处理图像文件的逻辑,现在我想用ViewComponent搜索并替换某些html中的所有img标签.在我这样做之前,我需要确保它甚至可以正常工作.

The backstory to this is that I've created a ViewComponent with some logic on how to handle image files, now I want to search and replace all img tags in some html with my ViewComponent. Before I do that I need to make sure this even works.

推荐答案

这就是我最终要做的事情:

This is what I ended up doing:

我将视图代码从MyComponent的Default.cshtml移到了部分视图( _myPartial ).然后,我使用了受这篇文章启发的IViewRenderService.

I moved the view code from the Default.cshtml for MyComponent to a partial view (_myPartial). Then I used a IViewRenderService inspired by this post.

然后我可以通过执行以下操作将视图模型传递给我,然后渲染并获取我的html字符串:

Then I could render and get my html string after passing in the viewmodel by doing this:

 var result = ViewRenderService.RenderToString("_myPartial", viewModel);

这篇关于在HTML字符串内渲染ViewComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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