Exemplo n.º 1
0
        protected async Task <string> RenderViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.ActionDescriptor.ActionName;
            }

            ViewData.Model = model;

            using (var writer = new System.IO.StringWriter())
            {
                ViewEngineResult viewResult =
                    _viewEngine.FindView(ControllerContext, viewName, true);

                ViewContext viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    ViewData,
                    TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
Exemplo n.º 2
0
        public ActionResult Index(int?id = null)
        {
            var availableLanguages = _localizationService.GetAllLanguages();

            if (id.HasValue)
            {
                var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
                var content        = umbracoContext.Content?.GetById(true, id.Value);
                if (content is null)
                {
                    return(NotFound());
                }

                availableLanguages = availableLanguages.Where(language => content.Cultures.ContainsKey(language.IsoCode));
            }
            var model = new BackOfficePreviewModel(_features, availableLanguages);

            if (model.PreviewExtendedHeaderView.IsNullOrWhiteSpace() == false)
            {
                var viewEngineResult = _viewEngines.FindView(ControllerContext, model.PreviewExtendedHeaderView !, false);
                if (viewEngineResult.View == null)
                {
                    throw new InvalidOperationException("Could not find the view " + model.PreviewExtendedHeaderView + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations));
                }
            }

            var viewPath = Path.Combine(
                _globalSettings.UmbracoPath,
                Constants.Web.Mvc.BackOfficeArea,
                ControllerExtensions.GetControllerName <PreviewController>() + ".cshtml")
                           .Replace("\\", "/"); // convert to forward slashes since it's a virtual path

            return(View(viewPath, model));
        }
        protected async Task <string> RenderAsync(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.RouteData.Values["action"].ToString();
            }

            ViewEngineResult viewResult = _compositeViewEngine.FindView(ControllerContext, viewName, false);

            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            using (var sw = new StringWriter())
            {
                var newViewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    viewDictionary,
                    TempData,
                    sw,
                    new HtmlHelperOptions());
                await viewResult.View.RenderAsync(newViewContext);

                return(sw.ToString());
            }
        }
Exemplo n.º 4
0
        private string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.ActionDescriptor.ActionName;
            }

            ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                ViewEngineResult viewResult =
                    _viewEngine.FindView(ControllerContext, viewName, false);

                ViewContext viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    ViewData,
                    TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                var t = viewResult.View.RenderAsync(viewContext);
                t.Wait();

                return(writer.GetStringBuilder().ToString());
            }
        }
Exemplo n.º 5
0
        public async Task <string> RenderPartialViewToString(Controller controller, string viewName, object model = null)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            controller.ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, false);

                ViewContext viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
        private async Task <string> RenderView(Controller controller, string viewName)
        {
            //Adapted from Red at https://stackoverflow.com/questions/40912375/return-view-as-string-in-net-core
            using (var writer = new StringWriter())
            {
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, true);

                if (viewResult.Success == false)
                {
                    return($"A view with the name {viewName} could not be found");
                }

                ViewContext viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
Exemplo n.º 7
0
        public async Task RenderViewAsync <TModel>(string name, TModel model, StringWriter output)
        {
            var actionContext = GetActionContext();

            var viewEngineResult = _viewEngine.FindView(actionContext, name, false);

            if (!viewEngineResult.Success)
            {
                throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name));
            }

            var view        = viewEngineResult.View;
            var viewContext = new ViewContext(
                actionContext,
                view,
                new ViewDataDictionary <TModel>(
                    new EmptyModelMetadataProvider(),
                    new ModelStateDictionary())
            {
                Model = model
            },
                new TempDataDictionary(
                    actionContext.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());

            await view.RenderAsync(viewContext);
        }
Exemplo n.º 8
0
        public async Task <string> RenderToStringAsync(string viewName, object model)
        {
            var httpContext = new DefaultHttpContext {
                RequestServices = _serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            using var sw = new StringWriter();
            var viewResult = _compositeViewEngine.FindView(actionContext, viewName, false);

            if (viewResult.View == null)
            {
                throw new ArgumentNullException($"{viewName} does not match any available view");
            }

            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                viewDictionary,
                new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                sw,
                new HtmlHelperOptions()
                );

            await viewResult.View.RenderAsync(viewContext);

            return(sw.ToString());
        }
    public string RenderPartialView(ActionContext context, string name, object model)
    {
        var viewEngineResult = _viewEngine.FindView(context, name, false);

        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name));
        }
        var view = viewEngineResult.View;

        using (var output = new StringWriter())
        {
            var viewContext = new ViewContext(
                context,
                view,
                new ViewDataDictionary(
                    new EmptyModelMetadataProvider(),
                    new ModelStateDictionary())
            {
                Model = model
            },
                new TempDataDictionary(
                    context.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());
            view.RenderAsync(viewContext).GetAwaiter().GetResult();
            return(output.ToString());
        }
    }
Exemplo n.º 10
0
        public async Task <IActionResult> Create([FromBody] Voucher voucher)
        {
            using var stringWriter     = new StringWriter();
            voucher.Logo               = Logo.GetLogo();
            voucher.BarCode            = "data:image/png;base64," + Convert.ToBase64String(QrCodeCreator.CreateQrCode(voucher.TicketNo));
            voucher.ValidPassengerIcon = IconToDisplay(voucher.TotalPersons, voucher.Passengers.Count);
            voucher.Facebook           = Facebook.GetLogo();
            voucher.YouTube            = YouTube.GetLogo();
            voucher.Instagram          = Instagram.GetLogo();
            var viewResult     = compositeViewEngine.FindView(ControllerContext, "Voucher", false);
            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = voucher
            };
            var viewContext = new ViewContext(ControllerContext, viewResult.View, viewDictionary, TempData, stringWriter, new HtmlHelperOptions());
            var htmlToPdf   = new HtmlToPdf(1000, 1414);
            await viewResult.View.RenderAsync(viewContext);

            var pdf      = htmlToPdf.ConvertHtmlString(stringWriter.ToString());
            var pdfBytes = pdf.Save();

            if (!Directory.Exists("Vouchers"))
            {
                Directory.CreateDirectory("Vouchers");
            }
            using (var streamWriter = new StreamWriter("Vouchers\\Voucher" + voucher.TicketNo + ".pdf")) {
                await streamWriter.BaseStream.WriteAsync(pdfBytes.AsMemory(0, pdfBytes.Length));
            }
            return(StatusCode(200, new {
                response = ApiMessages.FileCreated()
            }));
        }
Exemplo n.º 11
0
        /// <summary>Renders a (partial view) List to string.</summary>
        /// <param name="viewName">(Partial view) List to render</param>
        /// <param name="model">(Partial view) model to render</param>
        /// <returns>Rendered (partial view) List as string</returns>
        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.ActionDescriptor.DisplayName;
            }

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = _viewEngine.FindView(ControllerContext, viewName, false);

                ViewContext viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    ViewData,
                    TempData,
                    sw,
                    new HtmlHelperOptions() //Added this parameter in
                    );

                //Everything is async now!
                var t = viewResult.View.RenderAsync(viewContext);
                t.Wait();

                return(sw.GetStringBuilder().ToString());
            }
        }
        private async Task <string> RenderPartialViewToString(string viewName)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.ActionDescriptor.ActionName;
            }

            using (var writer = new StringWriter())
            {
                ViewEngineResult viewResult =
                    _viewEngine.FindView(ControllerContext, viewName, true);

                ViewContext viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    ViewData,
                    TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
Exemplo n.º 13
0
        public async Task <string> RenderViewToStringAsync(ControllerContext controllerContext, string viewName, object model, Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionary tempData, Dictionary <string, string> viewBagItems = null)
        {
            var view = _viewEngine.FindView(controllerContext, viewName, true).View;

            var writer = new StringWriter();

            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };


            var viewContext = new ViewContext(
                controllerContext, view, viewDictionary,
                tempData, writer, new HtmlHelperOptions()
                );

            if (viewBagItems != null)
            {
                foreach (var item in viewBagItems)
                {
                    viewContext.ViewData.Add(item.Key, item.Value);
                }
            }

            await view.RenderAsync(viewContext);

            return(writer.ToString());
        }
        public async Task <bool> RenderAsync(string name, object model, IOwinEnvironment context, CancellationToken cancellationToken)
        {
            var httpContext = context.Request[MicrosoftHttpContextKey] as HttpContext;

            if (httpContext == null)
            {
                _logger.Error($"Request dictionary does not contain '{MicrosoftHttpContextKey}'", nameof(RazorViewRenderer));
                return(false);
            }

            // TODO ideally this would be done by the existing middleware pipeline
            // if authentication and view rendering were split up
            GetUserIdentity(httpContext, _logger);

            var actionContext = GetActionContext(httpContext);

            ViewEngineResult viewEngineResult;

            if (IsApplicationRelativePath(name))
            {
                var basePath = Directory.GetCurrentDirectory();
                _logger.Trace($"Getting view '{name}' relative to '{basePath}'");
                viewEngineResult = _viewEngine.GetView(basePath, name, true);
            }
            else
            {
                viewEngineResult = _viewEngine.FindView(actionContext, name, true);
            }

            if (!viewEngineResult.Success)
            {
                _logger.Trace($"Could not find Razor view '{name}'", nameof(RazorViewRenderer));
                return(false);
            }

            var view = viewEngineResult.View;

            using (var writer = new StreamWriter(context.Response.Body))
            {
                var viewDataDictionary = new ViewDataDictionary(
                    new EmptyModelMetadataProvider(),
                    new ModelStateDictionary())
                {
                    Model = model
                };

                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewDataDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions());

                cancellationToken.ThrowIfCancellationRequested();
                await view.RenderAsync(viewContext);

                return(true);
            }
        }
Exemplo n.º 15
0
        public async Task <string> RenderViewAsString <TModel>(string viewName, TModel model)
        {
            var viewData = new ViewDataDictionary <TModel>(
                metadataProvider: new EmptyModelMetadataProvider(),
                modelState: new ModelStateDictionary())
            {
                Model = model
            };

            var actionContext = actionAccessor.ActionContext;

            var tempData = new TempDataDictionary(actionContext.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());
            }
        }
Exemplo n.º 16
0
        public async static Task <string> RenderPartialView(ViewContext context, string viewName, ICompositeViewEngine viewEngine = null, ViewEngineResult viewResult = null)
        {
            viewEngine ??= context.HttpContext.RequestServices.GetRequiredService <ICompositeViewEngine>();
            viewResult ??= viewEngine.FindView(context, viewName, false);

            await viewResult.View.RenderAsync(context);

            return(context.Writer.ToString());
        }
Exemplo n.º 17
0
        public IActionResult Index(int statusCode, [FromServices] ICompositeViewEngine compositeViewEngine)
        {
            var reExecute = this.HttpContext.Features.Get <IStatusCodeReExecuteFeature>();

            if (compositeViewEngine.FindView(this.ControllerContext, "Index", false).Success)
            {
                return(this.View(statusCode));
            }

            return(this.StatusCode(statusCode));
        }
Exemplo n.º 18
0
 //Put in BaseController
 public string RenderPartialViewToString(ICompositeViewEngine viewEngine, string viewName, object model)
 {
     viewName       = viewName ?? ControllerContext.ActionDescriptor.ActionName;
     ViewData.Model = model;
     using (StringWriter sw = new StringWriter())
     {
         IView       view        = viewEngine.FindView(ControllerContext, viewName, false).View;
         ViewContext viewContext = new ViewContext(ControllerContext, view, ViewData, TempData, sw, new HtmlHelperOptions());
         view.RenderAsync(viewContext).Wait();
         return(sw.GetStringBuilder().ToString());
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Ensures that a physical view file exists on disk.
        /// </summary>
        /// <param name="template">The view name.</param>
        protected bool EnsurePhsyicalViewExists(string template)
        {
            ViewEngineResult result = _compositeViewEngine.FindView(ControllerContext, template, false);

            if (result.View != null)
            {
                return(true);
            }

            _logger.LogWarning("No physical template file was found for template {Template}", template);
            return(false);
        }
        internal static async Task <string> RenderView <DataModel>(this Controller controller, ICompositeViewEngine viewEngine, string viewName, DataModel model)
        {
            var view = viewEngine.FindView(controller.ControllerContext, viewName, false).View;

            controller.ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                await view.RenderAsync(new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions()));

                return(writer.ToString());
            }
        }
        public async Task <Response> CreateReport([FromBody] InvoicingPrinterCriteria criteria, InvoicingPrinterVM report)
        {
            var viewResult     = compositeViewEngine.FindView(ControllerContext, "CreateReport", false);
            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = report
            };
            var viewContext = new ViewContext(ControllerContext, viewResult.View, viewDictionary, TempData, new StringWriter(), new HtmlHelperOptions());
            var result      = repo.Get(criteria);

            return(await repo.CreatePDF(viewResult, viewContext, result));
        }
Exemplo n.º 22
0
        public async Task <string> RenderToStringAsync(Controller controller, string viewName, object model)
        {
            using (var sw = new StringWriter())
            {
                var viewResult = _viewEngine.GetView(viewName, viewName, false);
                if (!viewResult.Success)
                {
                    viewResult = _viewEngine.FindView(controller.ControllerContext, viewName, false);
                }

                //if (!viewResult.Success)
                //{
                //    var endPointDisplay = controller.HttpContext.Request.GetEndpoint().DisplayName;

                //    if (endPointDisplay.Contains(".Areas."))
                //    {
                //        //search in Areas
                //        var areaName = endPointDisplay.Substring(endPointDisplay.IndexOf(".Areas.") + ".Areas.".Length);
                //        areaName = areaName.Substring(0, areaName.IndexOf(".Controllers."));

                //        var viewNamePath = $"~/Areas/{areaName}/views/{controller.HttpContext.Request.RouteValues["controller"]}/{controller.HttpContext.Request.RouteValues["action"]}.cshtml";

                //        viewResult = viewEngine.GetView(viewNamePath, viewNamePath, false);
                //    }

                //    if (!viewResult.Success)
                //        throw new Exception($"A view with the name '{viewNamePath}' could not be found");
                //}

                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"{viewName} does not match any available view");
                }

                //var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                //{
                //    Model = model
                //};

                var viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    sw,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
Exemplo n.º 23
0
        protected virtual async Task RenderPartialCoreAsync(
            string partialViewName,
            object model,
            ViewDataDictionary viewData,
            TextWriter writer)
        {
            if (partialViewName == null)
            {
                throw new ArgumentNullException(nameof(partialViewName));
            }

            var viewEngineResult = _viewEngine.GetView(
                ViewContext.ExecutingFilePath,
                partialViewName,
                isMainPage: false);
            var originalLocations = viewEngineResult.SearchedLocations;

            if (!viewEngineResult.Success)
            {
                viewEngineResult = _viewEngine.FindView(ViewContext, partialViewName, isMainPage: false);
            }

            if (!viewEngineResult.Success)
            {
                var locations = string.Empty;
                if (originalLocations.Any())
                {
                    locations = Environment.NewLine + string.Join(Environment.NewLine, originalLocations);
                }

                if (viewEngineResult.SearchedLocations.Any())
                {
                    locations +=
                        Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations);
                }

                throw new InvalidOperationException(
                          Resources.FormatViewEngine_PartialViewNotFound(partialViewName, locations));
            }

            var view = viewEngineResult.View;

            using (view as IDisposable)
            {
                // Determine which ViewData we should use to construct a new ViewData
                var baseViewData = viewData ?? ViewData;

                var newViewData = new ViewDataDictionary <object>(baseViewData, model);
                var viewContext = new ViewContext(ViewContext, view, newViewData, writer);

                await viewEngineResult.View.RenderAsync(viewContext);
            }
        }
Exemplo n.º 24
0
    public async Task <string> RenderToStringAsync(string viewName, object model, ViewDataDictionary viewDataDictionary)
    {
        var controller = string.Empty;

        viewName = viewName?.TrimStart(new char[] { '/' });
        Regex rex   = new Regex(@"^(\w+)\/(.*)$");
        Match match = rex.Match(viewName);

        if (match.Success)
        {
            controller = match.Groups[1].Value;
            viewName   = match.Groups[2].Value;
        }
        var routeData = new RouteData();

        routeData.Values.Add(ControllerStr, controller);
        var actionContext = new ActionContext(_context, routeData, new ActionDescriptor());
        var viewResult    = _viewEngine.FindView(actionContext, viewName, false);

        if (viewResult.View == null)
        {
            Console.WriteLine($"Searched the following locations: {string.Join(", ", viewResult.SearchedLocations)} for folder \"{controller}\" and view \"{viewName}\"");
            throw new ArgumentNullException($"{viewName} does not match any available view");
        }
        var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
        {
            Model = model
        };

        if (viewDataDictionary != null)
        {
            foreach (var obj in viewDataDictionary)
            {
                viewDictionary.Add(obj);
            }
        }
        using (var sw = new StringWriter())
        {
            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                viewDictionary,
                new TempDataDictionary(_context, _tempDataProvider),
                sw,
                new HtmlHelperOptions()
                );
            viewContext.RouteData = _context.GetRouteData();
            await viewResult.View.RenderAsync(viewContext);

            return(sw.ToString());
        }
    }
Exemplo n.º 25
0
        public ActionResult Details(
            [FromServices] ICompositeViewEngine compositeViewEngine,
            [FromServices] IActionContextAccessor actionContextAccessor,
            string key)
        {
            var result = compositeViewEngine.FindView(actionContextAccessor.ActionContext, key, false);

            if (result.Success)
            {
                return(View(key));
            }
            return(NotFound());
        }
Exemplo n.º 26
0
        protected async Task <string> RenderPartail(string viewName, object model)
        {
            ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult  = _viewEngine.FindView(_actionAccessor.ActionContext, viewName, false);
                ViewContext      viewContext = new ViewContext(_actionAccessor.ActionContext, viewResult.View, ViewData, TempData, sw, new HtmlHelperOptions());

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
Exemplo n.º 27
0
        protected async System.Threading.Tasks.Task <ContentResult> RenderCssAsync(string viewName, object model)
        {
            ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult  = _viewEngine.FindView(_actionAccessor.ActionContext, viewName, true);
                ViewContext      viewContext = new ViewContext(_actionAccessor.ActionContext, viewResult.View, ViewData, TempData, sw, new HtmlHelperOptions());

                await viewResult.View.RenderAsync(viewContext);

                return(Content(sw.ToString(), "text/css", System.Text.Encoding.UTF8));
            }
        }
Exemplo n.º 28
0
        public IActionResult Index(string section = "home", string content = "index")
        {
            // Note: Indicate the current controller-specific directory ("Organization") with the "./" prefix
            var view   = $"./{_tenantContext.SiteContext.FolderName}/{section}/{content}";
            var result = _viewEngine.FindView(_actionContext, view, false);

            if (!result.Success)
            {
                return(NotFound());
            }

            // give the full absolute view path as argument, so searching the view won't run a second time
            return(View(result.View.Path));
        }
Exemplo n.º 29
0
        protected string RenderViewAsString(object model, string viewName = null)
        {
            viewName       = viewName ?? ControllerContext.ActionDescriptor.ActionName;
            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                IView       view        = viewEngine.FindView(ControllerContext, viewName, true).View;
                ViewContext viewContext = new ViewContext(ControllerContext, view, ViewData, TempData, sw, new HtmlHelperOptions());

                view.RenderAsync(viewContext).Wait();

                return(sw.GetStringBuilder().ToString());
            }
        }
Exemplo n.º 30
0
        private string RenderPartialViewToString(string viewName, object model)
        {
            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = viewEngine.FindView(ControllerContext, viewName, false);

                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw, new HtmlHelperOptions());

                var t = viewResult.View.RenderAsync(viewContext);
                t.Wait();

                return(sw.GetStringBuilder().ToString());
            }
        }