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

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

    I saw an implementation for MVC 3 and Razor from another website, it worked for me:

        public static string RazorRender(Controller context, string DefaultAction)
        {
            string Cache = string.Empty;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.TextWriter tw = new System.IO.StringWriter(sb); 
    
            RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
            view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);
    
            Cache = sb.ToString(); 
    
            return Cache;
    
        } 
    
        public static string RenderRazorViewToString(string viewName, object model)
        {
    
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        } 
    
        public static class HtmlHelperExtensions
        {
            public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
            {
                ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);
    
                if (result.View != null)
                {
                    StringBuilder sb = new StringBuilder();
                    using (StringWriter sw = new StringWriter(sb))
                    {
                        using (HtmlTextWriter output = new HtmlTextWriter(sw))
                        {
                            ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                            result.View.Render(viewContext, output);
                        }
                    }
                    return sb.ToString();
                } 
    
                return String.Empty;
    
            }
    
        }
    

    More on Razor render- MVC3 View Render to String

提交回复
热议问题