假设我有一个名为 MyComponent 的 ViewComponent。
从 ASP.NET Core 1.1 开始,我可以通过在 razor view .cshtml 页面中编写此 ViewComponent 来呈现此 ViewComponent:
<vc:my-component></vc:my-component>
我想做这样的事情:
@{string myHtml = "<vc:my-component></vc:my-component>";}
@(new HtmlString(myHtml))
我通过这样做安装并尝试了 RazorEngine,但这不起作用:
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 文件中:
@(new HtmlString(ViewBag.result))
背景故事是我创建了一个 ViewComponent,其中包含一些有关如何处理图像文件的逻辑,现在我想用我的 ViewComponent 搜索并替换某些 html 中的所有 img 标签。在我这样做之前,我需要确保它有效。
检查github上这个url的代码:
https://gist.github.com/pauldotknopf/b424e9b8b03d31d67f3cce59f09ab17f https://gist.github.com/pauldotknopf/b424e9b8b03d31d67f3cce59f09ab17f
Code
public class HomeController : Controller {
public async Task<string> RenderViewComponent(string viewComponent, object args) {
var sp = HttpContext.RequestServices;
var helper = new DefaultViewComponentHelper(
sp.GetRequiredService<IViewComponentDescriptorCollectionProvider>(),
HtmlEncoder.Default,
sp.GetRequiredService<IViewComponentSelector>(),
sp.GetRequiredService<IViewComponentInvokerFactory>(),
sp.GetRequiredService<IViewBufferScope>());
using (var writer = new StringWriter()) {
var context = new ViewContext(ControllerContext, NullView.Instance, ViewData, TempData, writer, new HtmlHelperOptions());
helper.Contextualize(context);
var result = await helper.InvokeAsync(viewComponent, args);
result.WriteTo(writer, HtmlEncoder.Default);
await writer.FlushAsync();
return writer.ToString();
}
}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)