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

后端 未结 15 3008
挽巷
挽巷 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:01

    Here is a class I wrote to do this for ASP.NETCore RC2. I use it so I can generate html email using Razor.

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Abstractions;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.ViewEngines;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using Microsoft.AspNetCore.Routing;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace cloudscribe.Web.Common.Razor
    {
        /// 
        /// the goal of this class is to provide an easy way to produce an html string using 
        /// Razor templates and models, for use in generating html email.
        /// 
        public class ViewRenderer
        {
            public ViewRenderer(
                ICompositeViewEngine viewEngine,
                ITempDataProvider tempDataProvider,
                IHttpContextAccessor contextAccesor)
            {
                this.viewEngine = viewEngine;
                this.tempDataProvider = tempDataProvider;
                this.contextAccesor = contextAccesor;
            }
    
            private ICompositeViewEngine viewEngine;
            private ITempDataProvider tempDataProvider;
            private IHttpContextAccessor contextAccesor;
    
            public async Task RenderViewAsString(string viewName, TModel model)
            {
    
                var viewData = new ViewDataDictionary(
                            metadataProvider: new EmptyModelMetadataProvider(),
                            modelState: new ModelStateDictionary())
                {
                    Model = model
                };
    
                var actionContext = new ActionContext(contextAccesor.HttpContext, new RouteData(), new ActionDescriptor());
                var tempData = new TempDataDictionary(contextAccesor.HttpContext, tempDataProvider);
    
                using (StringWriter output = new StringWriter())
                {
    
                    ViewEngineResult viewResult = viewEngine.FindView(actionContext, viewName, true);
    
                    ViewContext viewContext = new ViewContext(
                        actionContext,
                        viewResult.View,
                        viewData,
                        tempData,
                        output,
                        new HtmlHelperOptions()
                    );
    
                    await viewResult.View.RenderAsync(viewContext);
    
                    return output.GetStringBuilder().ToString();
                }
            }
        }
    }
    

提交回复
热议问题