Render ViewComponent inside html string

安稳与你 提交于 2020-01-05 05:56:53

问题


Lets say I have a ViewComponent named MyComponent.

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>

I want to do something like this:

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

@(new HtmlString(myHtml))

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;

then in the .chtml file:

 @(new HtmlString(ViewBag.result))

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.


回答1:


This is what I ended up doing:

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.

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

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



回答2:


Check the code at this url on github:

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();
    }
  }}



来源:https://stackoverflow.com/questions/43225789/render-viewcomponent-inside-html-string

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