Пример #1
0
        public async Task <string> RenderViewToString <TModel>(string name, TModel model)
        {
            var actionContext = GetActionContext();

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

            if (!viewEngineResult.Success)
            {
                throw new InvalidOperationException(string.Format("Couldn't find view '{0}' \nSerched location: {1}", name, viewEngineResult.SearchedLocations.Aggregate((x, y) => x + ";\n" + y)));
            }

            var view = viewEngineResult.View;

            using (var output = new StringWriter())
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    new ViewDataDictionary <TModel>(
                        metadataProvider: new EmptyModelMetadataProvider(),
                        modelState: new ModelStateDictionary())
                {
                    Model = model
                },
                    new TempDataDictionary(
                        actionContext.HttpContext,
                        _tempDataProvider),
                    output,
                    new HtmlHelperOptions());

                await view.RenderAsync(viewContext);

                return(output.ToString());
            }
        }
Пример #2
0
        public async Task <string> RenderTemplateAsync <T>(string filename, T viewmodel, bool isFullPathProvider = false)
        {
            var httpcontext = new DefaultHttpContext
            {
                RequestServices = _serviceprovider
            };

            var actionContext = new ActionContext(httpcontext, new RouteData(), new ActionDescriptor());

            using (var outputWriter = new StringWriter())
            {
                var ViewResult = _viewEngine.FindView(actionContext, filename, false);
                if (ViewResult.View == null)
                {
                    throw new ArgumentNullException($"{filename} does not match with available view");
                }
                var viewDictionary = new ViewDataDictionary <T>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = viewmodel
                };
                var tempDataDictionary = new TempDataDictionary(httpcontext, _tempDataProvider);

                var ViewContext = new ViewContext(
                    actionContext,
                    ViewResult.View,
                    viewDictionary,
                    tempDataDictionary,
                    outputWriter, new HtmlHelperOptions());

                await ViewResult.View.RenderAsync(ViewContext);

                return(outputWriter.ToString());
            }
        }
        public async Task <string> GetRawHtmlAsync(string view, EmailViewModel viewModel)
        {
            // Inspired by: https://stackoverflow.com/a/40932984

            DefaultHttpContext defaultHttpContext = new DefaultHttpContext()
            {
                RequestServices = _serviceProvider
            };
            ActionContext      actionContext      = new ActionContext(defaultHttpContext, new RouteData(), new ActionDescriptor());
            ViewDataDictionary viewDataDictionary =
                new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = viewModel
            };

            ViewEngineResult result = _razorViewEngine.FindView(actionContext, view, false);

            bool hasNoResult = result.View == null;

            if (hasNoResult)
            {
                return(null);
            }

            using (StringWriter stringWriter = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(actionContext, result.View, viewDataDictionary,
                                                          new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), stringWriter, new HtmlHelperOptions());

                await result.View.RenderAsync(viewContext);

                return(stringWriter.ToString());
            }
        }
        private IView FindView(ActionContext actionContext, string viewName)
        {
            var getViewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);

            if (getViewResult.Success)
            {
                return(getViewResult.View);
            }

            var findViewResult = _viewEngine.FindView(actionContext, viewName, isMainPage: true);

            if (findViewResult.Success)
            {
                return(findViewResult.View);
            }

            var searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations);
            var errorMessage      = string.Join(
                Environment.NewLine,
                new[]
            {
                $"Unable to find view '{viewName}'. The following locations were searched:"
            }
                .Concat(searchedLocations));

            throw new InvalidOperationException(errorMessage);
        }
Пример #5
0
        public async Task <string> RenderView <TModel>(string viewName, TModel model) where TModel : class
        {
            var actionContext = GetActionContext();
            var viewResult    = _viewEngine.FindView(actionContext, viewName, false);

            if (!viewResult.Success)
            {
                throw new InvalidOperationException($"Failed to locate view '{viewName}'");
            }

            using (var sw = new StringWriter())
            {
                var viewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };
                var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);

                var viewContext = new ViewContext(actionContext, viewResult.View, viewData, tempData, sw, new HtmlHelperOptions());

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
Пример #6
0
        private static async Task <string> RenderView <TModel>(IRazorViewEngine razorViewEngine, ITempDataProvider tempDataProvider, HttpContext httpContext, string viewName, TModel model)
        {
            var routeData    = ExtractRouteData(viewName);
            var templateName = routeData.Values["action"].ToString();

            var actionContext    = new ActionContext(httpContext, routeData, new ActionDescriptor());
            var viewEngineResult = razorViewEngine.FindView(actionContext, templateName, true);

            if (false == viewEngineResult.Success)
            {
                // fail
                var locations = String.Join(" ", viewEngineResult.SearchedLocations);
                throw new Exception($"Could not find view with the name '{templateName}'. Looked in {locations}.");
            }
            else // Success
            {
                var view         = viewEngineResult.View;
                var viewDataDict = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };
                var tempDataDict      = new TempDataDictionary(actionContext.HttpContext, tempDataProvider);
                var htmlHelperOptions = new HtmlHelperOptions();
                using (var output = new StringWriter())
                {
                    var viewContext = new ViewContext(actionContext, view, viewDataDict, tempDataDict, output, htmlHelperOptions);
                    await view.RenderAsync(viewContext);

                    return(output.ToString());
                }
            }
        }
        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 = _razorViewEngine.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());
            }
        }
Пример #8
0
        public string Render <TModel>(string name, TModel model, bool _isMainPage = false)
        {
            var actionContext    = GetActionContext();
            var viewEngineResult = _viewEngine.FindView(actionContext, name, isMainPage: _isMainPage);

            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(
                    actionContext,
                    view,
                    new ViewDataDictionary <TModel>(
                        metadataProvider: new EmptyModelMetadataProvider(),
                        modelState: new ModelStateDictionary())
                {
                    Model = model
                },
                    new TempDataDictionary(
                        actionContext.HttpContext,
                        _tempDataProvider),
                    output,
                    new HtmlHelperOptions());
                view.RenderAsync(viewContext).GetAwaiter().GetResult();
                return(output.ToString());
            }
        }
Пример #9
0
        public string ToHtml(string name, ViewDataDictionary viewData)
        {
            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;

            using (var output = new StringWriter())
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    new TempDataDictionary(
                        actionContext.HttpContext,
                        _tempDataProvider),
                    output,
                    new HtmlHelperOptions());

                view.RenderAsync(viewContext).GetAwaiter().GetResult();

                return(output.ToString());
            }
        }
Пример #10
0
        public async Task <string> Render <TModel>(string viewPath, TModel model)
        {
            var httpContext = _httpContextAccessor.HttpContext;

            var routeData = httpContext.GetRouteData();

            var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor());

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

            if (!viewEngineResult.Success)
            {
                throw new InvalidOperationException($"Couldn't find view {viewPath}");
            }

            using var output = new StringWriter();

            var view = viewEngineResult.View;

            var viewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            var tempData = new TempDataDictionary(httpContext, _tempDataProvider);

            var viewContext = new ViewContext(actionContext, view, viewData, tempData, output, new HtmlHelperOptions());

            await view.RenderAsync(viewContext);

            return(output.ToString());
        }
Пример #11
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 httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
            //var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            //var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);
            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());
            }
        }
Пример #12
0
        public async Task <string> RenderAsync(string viewName, object viewModel, HttpContext httpContext, ActionContext actionContext)
        {
            using (var sw = new StringWriter())
            {
                var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

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

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

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

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
        ///<inheritdoc/>
        public async Task <string> RenderAsync(HttpContext httpContext, string viewName, object model, IDictionary <string, object> viewData, bool fromCustomPath = false)
        {
            var actionContext = new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor());
            var viewResult    = fromCustomPath
                ? _razorViewEngine.GetView(null, viewName, false)
                : _razorViewEngine.FindView(actionContext, viewName, false);

            using (var writer = new StringWriter())
            {
                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"{viewResult.ViewName} does not match any available view");
                }

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

                if (viewData != null && viewData.Count > 0)
                {
                    foreach (var kv in viewData)
                    {
                        viewDictionary[kv.Key] = kv.Value;
                    }
                }

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

                await viewResult.View.RenderAsync(viewContext).ConfigureAwait(false);

                return(writer.ToString());
            }
        }
        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 writer = new StringWriter())
            {
                var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

                if (viewResult == null)
                {
                    Console.WriteLine("Not found " + viewName);
                    return(null);
                }

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

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

                await viewResult.View.RenderAsync(viewContext);

                return(writer.ToString());
            }
        }
        public async Task <string> RenderViewToStringAsync <TModel>(string viewName, TModel model)
        {
            var actionContext    = GetActionContext();
            var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);

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

            var view     = viewEngineResult.View;
            var viewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            using (var output = new StringWriter())
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    output,
                    new HtmlHelperOptions()
                    );
                await view.RenderAsync(viewContext);

                return(output.ToString());
            }
        }
Пример #16
0
        /// <summary>
        /// Renders the view to a string using a view location.
        /// </summary>
        /// <param name="httpContext">The http context.</param>
        /// <param name="viewName">The view name.</param>
        /// <param name="model">The view model.</param>
        /// <param name="viewData">The view data.</param>
        /// <param name="fromCustomPath">Determines whether the service should search views in non default locations.</param>
        /// <returns>The action task.</returns>
        public Task <string> RenderAsync(HttpContext httpContext, string viewName, object model, IDictionary <string, object> viewData, bool fromCustomPath)
        {
            var actionContext = new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor());
            var viewResult    = fromCustomPath
                ? _razorViewEngine.GetView(null, viewName, false)
                : _razorViewEngine.FindView(actionContext, viewName, false);

            return(RenderToStringAsync(actionContext, viewResult, model, viewData));
        }
Пример #17
0
        public async Task <string> TransformAsync(string templateName, object model)
        {
            if (string.IsNullOrWhiteSpace(templateName))
            {
                throw new ArgumentException("Non-empty value expected", nameof(templateName));
            }
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var httpContext = new DefaultHttpContext {
                RequestServices = _serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var viewLocation = BuildViewLocation(templateName);

            _logger.Debug($"RenderToStringAsync before finding view {templateName}");
            var viewResult = _razorViewEngine.FindView(actionContext, viewLocation, false);

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

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

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

                _logger.Debug($"RenderToStringAsync before rendering view with context");
                try
                {
                    await viewResult.View.RenderAsync(viewContext);
                }
                catch (Exception e)
                {
                    _logger.Error("Error rendering razor view", e);
                }

                return(sw.ToString());
            }
        }
Пример #18
0
        public async Task <string> RenderToStringAsync(string viewName, object model)
        {
            try
            {
                var httpContext = new DefaultHttpContext {
                    RequestServices = _serviceProvider
                };
                var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

                using (var sw = new StringWriter())
                {
                    IView view          = null;
                    var   getViewResult = _razorViewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
                    if (getViewResult.Success)
                    {
                        view = getViewResult.View;
                    }

                    if (view == null)
                    {
                        var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);
                        view = viewResult?.View;
                    }

                    if (view == null)
                    {
                        LogHelper.Warn("ViewRenderService", "没有找到对应的view:" + viewName);
                        return(string.Empty);
                    }

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

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

                    await view.RenderAsync(viewContext);

                    return(sw.ToString());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("ViewRenderService", "找view出错了:" + viewName, ex);
                return(string.Empty);
            }
        }
Пример #19
0
        public async Task <string> RenderToStringAsync <TModel>(string viewName, TModel model, ViewDataDictionary viewData)
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext {
                    RequestServices = _serviceProvider
                };
                //var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
                var actionContext = _actionContextAccessor.ActionContext ?? new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

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


                    // Fallback - the above seems to consistently return null when using the EmbeddedFileProvider
                    if (viewResult.View == null)
                    {
                        viewResult = _viewEngine.GetView("~/", viewName, false);
                    }

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

                    viewData.Model = model;
                    var viewDictionary = viewData;

                    //var viewDictionary = new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(),
                    //        _actionContextAccessor.ActionContext?.ModelState ?? 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());
                }
            }
            catch
            {
                throw;
            }
        }
Пример #20
0
        public async Task <string> RenderToStringAsync(string viewName, object model)
        {
            if (HttpContext == null)
            {
                HttpContext = new DefaultHttpContext {
                    RequestServices = _serviceProvider
                };
            }

            if (ActionContext == null)
            {
                ActionContext = new ActionContext(HttpContext, new RouteData(), new ActionDescriptor());
            }

            using (var sw = new StringWriter())
            {
                if (viewName.StartsWith("~/Views/", StringComparison.CurrentCultureIgnoreCase))
                {
                    viewName = viewName.Replace("~/Views/", "", StringComparison.CurrentCultureIgnoreCase);
                }

                if (viewName.EndsWith(".cshtml", StringComparison.CurrentCultureIgnoreCase))
                {
                    viewName = viewName.Replace(".cshtml", "", StringComparison.CurrentCultureIgnoreCase);
                }

                var viewResult = _razorViewEngine.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(HttpContext, _tempDataProvider),
                    sw,
                    new HtmlHelperOptions()
                    );

                viewContext.HttpContext = HttpContext;

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
Пример #21
0
        public async Task <string> RenderToStringAsync(string viewName, object model = null, RouteData routeData = null, bool useActionContext = false)
        {
            ActionContext actionContext;

            if (routeData == null)
            {
                actionContext = ActionContext;
            }
            else
            {
                actionContext = new ActionContext(
                    httpContextAccessor == null ? new DefaultHttpContext {
                    RequestServices = serviceProvider
                } : httpContextAccessor.HttpContext,
                    routeData,
                    new ActionDescriptor());
            }

            using (var stringWriter = new StringWriter())
            {
                ViewEngineResult viewResult;
                if (useActionContext)
                {
                    viewResult = razorViewEngine.FindView(actionContext, viewName, false);
                }
                else
                {
                    viewResult = razorViewEngine.GetView(viewName, viewName, false);
                }

                if (viewResult.View == null)
                {
                    throw new ArgumentNullException("View", $"{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),
                    stringWriter,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(stringWriter.ToString());
            }
        }
Пример #22
0
        public string RenderToString <T>(string viewName, T model)
        {
            var httpContext = new DefaultHttpContext {
                RequestServices = serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            using (var sw = new StringWriter())
            {
                var viewResult = razorViewEngine.FindView(actionContext, viewName, false);
                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"{viewName} does not match any available view");
                }

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

                if (viewResult.View is RazorView razorView && razorView.RazorPage is PageBase razorPage)
                {
                    razorPage.PageContext = new PageContext(actionContext)
                    {
                        ViewData = viewDictionary,
                    };
                }

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

                viewResult.View.RenderAsync(viewContext).Wait();
                return(sw.ToString());
            }
        }
Пример #23
0
        public async Task <string> RenderTemplateAsync <TViewModel>(RouteData routeData, ActionDescriptor actionDescriptor,
                                                                    string viewName, TViewModel viewModel, Dictionary <string, object> additonalViewDictionary = null, bool isMainPage = true) where TViewModel : IViewData
        {
            var httpContext = new DefaultHttpContext
            {
                RequestServices = _serviceProvider
            };

            var actionContext = new ActionContext(httpContext, routeData, actionDescriptor);

            using (var outputWriter = new StringWriter())
            {
                var viewResult     = _viewEngine.FindView(actionContext, viewName, isMainPage);
                var viewDictionary = new ViewDataDictionary <TViewModel>(viewModel.ViewData, viewModel);
                if (additonalViewDictionary != null)
                {
                    foreach (var kv in additonalViewDictionary)
                    {
                        if (!viewDictionary.ContainsKey(kv.Key))
                        {
                            viewDictionary.Add(kv);
                        }
                        else
                        {
                            viewDictionary[kv.Key] = kv.Value;
                        }
                    }
                }

                var tempDataDictionary = new TempDataDictionary(httpContext, _tempDataProvider);

                if (!viewResult.Success)
                {
                    throw new TemplateServiceException($"Failed to render template {viewName} because it was not found.");
                }

                try
                {
                    var viewContext = new ViewContext(actionContext, viewResult.View, viewDictionary,
                                                      tempDataDictionary, outputWriter, new HtmlHelperOptions());

                    await viewResult.View.RenderAsync(viewContext);
                }
                catch (Exception ex)
                {
                    throw new TemplateServiceException("Failed to render template due to a razor engine failure", ex);
                }

                await outputWriter.FlushAsync();

                return(outputWriter.ToString());
            }
        }
Пример #24
0
        private IView GetView(ActionContext actionContext, string viewName)
        {
            var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

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

            return(viewResult.View);
        }
Пример #25
0
 public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
 {
     _locker.EnterReadLock();
     try
     {
         return(_current.FindView(context, viewName, isMainPage));
     }
     finally
     {
         _locker.ExitReadLock();
     }
 }
Пример #26
0
        public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
        {
            if (viewName.StartsWith("Components", StringComparison.InvariantCultureIgnoreCase))
            {
                const char separator = '/';
                viewName = string.Join(separator, viewName.Split(separator).Skip(2));
            }

            var result = _razor.FindView(context, viewName, isMainPage);

            return(result);
        }
        public string RenderPartial(HttpContext context, string viewName, object model = null, Dictionary <string, object> viewData = null)
        {
            ActionContext actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor());


            using (var sw = new StringWriter())
            {
                using (var c = SW.Measure())
                {
                    ViewEngineResult viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

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

                    var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());

                    if (model != null)
                    {
                        viewDictionary.Model = model;
                    }

                    if (viewData != null)
                    {
                        foreach (var item in viewData)
                        {
                            viewDictionary[item.Key] = item.Value;
                        }
                    }

                    var opts = new HtmlHelperOptions();

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

                    var t = RenderAsync(viewResult, viewContext);
                    t.Wait();
                    if (t.Result.Code != 200)
                    {
                        throw new CodeShellHttpException(t.Result);
                    }
                    return(sw.ToString());
                }
            }
        }
Пример #28
0
        /// <inheritdoc />
        public async Task <string> RenderViewToStringAsync <TModel>(string viewName, TModel model, ExpandoObject viewBag = null, bool isMainPage = true)
        {
            ActionContext actionContext = GetActionContext();
            var           viewResult    = viewEngine.FindView(actionContext, viewName, isMainPage);

            // Fallback - the above seems to consistently return null when using the EmbeddedFileProvider
            if (viewResult.View == null)
            {
                viewResult = viewEngine.GetView("~/", viewName, isMainPage);
            }

            return(await RenderViewAsync(viewResult.View, actionContext, model, viewBag));
        }
Пример #29
0
        /// <summary>
        /// Renders the partial view indicated by the specified name to an HTML string, using the specified model.
        /// </summary>
        /// <typeparam name="TModel">Represents the model type with which to render the partial view.</typeparam>
        /// <param name="partialName">Represents the name of the partial view to be rendered.</param>
        /// <param name="model">Represents the model with which to render the partial view.</param>
        public async Task <string> RenderPartialToStringAsync <TModel>(string partialName, TModel model)
        {
            // Get the action context.
            var actionContext = new ActionContext(new DefaultHttpContext {
                RequestServices = _serviceProvider
            }, new RouteData(), new ActionDescriptor());
            // Try to get the partial view with the provided name.
            var getPartialResult = _viewEngine.FindView(actionContext, partialName, false);

            // Check if there were any errors getting the partial view.
            if (!getPartialResult.Success)
            {
                // Throw an error.
                throw new InvalidOperationException($"Unable to find the requested partial {partialName} in {string.Join(", ", getPartialResult.SearchedLocations)}.");
            }
            // Get the actual partial view.
            var partial = getPartialResult.View;
            // Define the variable to store the string.
            var viewContent = string.Empty;

            // Define a new string writer.
            using (var output = new StringWriter())
            {
                // Get the view context.
                var viewContext = new ViewContext
                                  (
                    actionContext,
                    partial,
                    new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                },
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    output,
                    new HtmlHelperOptions()
                                  );
                // Render the partial within the view context.
                await partial.RenderAsync(viewContext);

                // And return the string.
                viewContent = output.ToString();
            }
            // Check if there were any errors in rendering the partial view.
            if (string.IsNullOrEmpty(viewContent))
            {
                // Return an error.
                throw new InvalidOperationException($"Error: An error occured while rendering the requested partial {partialName}.");
            }
            // Return the string.
            return(viewContent);
        }
        public RazorViewRenderer PrepareView(string viewName)
        {
            actionContext = BuildActionContext();

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

            if (!viewEngineResult.Success)
            {
                throw new InvalidOperationException(string.Format(Resources.NoView, viewName));
            }

            view = viewEngineResult.View;
            return(this);
        }