How to render an ASP.NET MVC view as a string?

后端 未结 15 2959
挽巷
挽巷 2020-11-21 04:40

I want to output two different views (one as a string that will be sent as an email), and the other the page displayed to a user.

Is this possible in ASP.NET MVC bet

15条回答
  •  醉酒成梦
    2020-11-21 05:10

    Additional tip for ASP NET CORE:

    Interface:

    public interface IViewRenderer
    {
      Task RenderAsync(Controller controller, string name, TModel model);
    }
    

    Implementation:

    public class ViewRenderer : IViewRenderer
    {
      private readonly IRazorViewEngine viewEngine;
    
      public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;
    
      public async Task RenderAsync(Controller controller, string name, TModel model)
      {
        ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);
    
        if (!viewEngineResult.Success)
        {
          throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
        }
    
        IView view = viewEngineResult.View;
        controller.ViewData.Model = model;
    
        await using var writer = new StringWriter();
        var viewContext = new ViewContext(
           controller.ControllerContext,
           view,
           controller.ViewData,
           controller.TempData,
           writer,
           new HtmlHelperOptions());
    
           await view.RenderAsync(viewContext);
    
           return writer.ToString();
      }
    }
    

    Registration in Startup.cs

    ...
     services.AddSingleton();
    ...
    

    And usage in controller:

    public MyController: Controller
    {
      private readonly IViewRenderer renderer;
      public MyController(IViewRendere renderer) => this.renderer = renderer;
      public async Task MyViewTest
      {
        var view = await this.renderer.RenderAsync(this, "MyView", model);
        return new OkObjectResult(view);
      }
    }
    

提交回复
热议问题