Пример #1
0
        public async Task <string> RenderViewAsync <TModel>(Controller controller, string viewName, TModel model, bool isPartialView = false)
        {
            _ = controller ?? throw new ArgumentNullException(nameof(controller));

            controller.ViewData.Model = model;

            using var writer = new StringWriter();
            IViewEngine      viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = viewEngine.GetView(viewName, viewName, !isPartialView);

            if (!viewResult.Success)
            {
                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).ConfigureAwait(false);

            return(writer.GetStringBuilder().ToString());
        }
Пример #2
0
 public ViewEngineResult GetView(string?executingFilePath, string viewPath, bool isMainPage)
 {
     using (_profiler.Step(string.Format("{0}.GetView, {1}, {2}, {3}", _name, executingFilePath, viewPath, isMainPage)))
     {
         return(Inner.GetView(executingFilePath, viewPath, isMainPage));
     }
 }
        public static async Task <string> RenderViewAsync(
            this Controller controller,
            string templateName,
            string viewName)
        {
            using (var writer = new StringWriter())
            {
                string           ViewLocation = $"~/Views/{templateName}/{viewName}.cshtml";
                IViewEngine      viewEngine   = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult   = viewEngine.GetView(ViewLocation, ViewLocation, 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());
            }
        }
Пример #4
0
        public static async Task <HtmlString> RenderViewAsync(this TabbedContent tab, string viewName, HttpContext context, ITempDataDictionary tempDataDictionary)
        {
            using (var writer = new StringWriter())
            {
                IViewEngine      viewEngine    = context.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                var              actionContext = new ActionContext(context, new Microsoft.AspNetCore.Routing.RouteData(), new ActionDescriptor());
                ViewEngineResult viewResult    = viewEngine.GetView(viewName, viewName, false);

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

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

                ViewContext viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    tempDataDictionary,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(new HtmlString(writer.GetStringBuilder().ToString()));
            }
        }
Пример #5
0
        public static async Task <string> RenderViewAsync <TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            controller.ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                IViewEngine      viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.GetView(viewName, viewName, !partial);

                if (viewResult.Success == false)
                {
                    return(null);
                }

                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 static ViewEngineResult GetViewEngineResult(ControllerBase controller, string viewName, bool isPartial, IViewEngine viewEngine)
        {
            if (!viewName.StartsWith("~/"))
            {
                return(viewEngine.FindView(controller.ControllerContext, viewName, !isPartial));
            }
            var hostingEnv = controller.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)) as
                             IWebHostEnvironment;

            return(viewEngine.GetView(hostingEnv?.WebRootPath ?? Environment.WebRootPath, viewName, !isPartial));
        }
Пример #7
0
 private ViewEngineResult GetViewEngineResult(string viewName, bool isPartial, IViewEngine viewEngine)
 {
     if (viewName.StartsWith("~/"))
     {
         var hostingEnv = HttpContext.RequestServices.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;
         return(viewEngine.GetView(hostingEnv.WebRootPath, viewName, !isPartial));
     }
     else
     {
         return(viewEngine.FindView(ControllerContext, viewName, !isPartial));
     }
 }
        /// <summary>
        /// Render a partial view to string.
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="controller"></param>
        /// <param name="viewNamePath"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static async Task <string> RenderViewToStringAsync <TModel>(this Controller controller,
                                                                           string viewNamePath, TModel model)
        {
            if (string.IsNullOrEmpty(viewNamePath))
            {
                viewNamePath = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            controller.ViewData.Model = model;

            using (StringWriter writer = new StringWriter())
            {
                try
                {
                    IViewEngine viewEngine =
                        controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as
                        ICompositeViewEngine;

                    ViewEngineResult viewResult = null;

                    if (viewNamePath.EndsWith(".cshtml"))
                    {
                        viewResult = viewEngine.GetView(viewNamePath, viewNamePath, false);
                    }
                    else
                    {
                        viewResult = viewEngine.FindView(controller.ControllerContext, viewNamePath, false);
                    }

                    if (!viewResult.Success)
                    {
                        return($"A view with the name '{viewNamePath}' 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());
                }
                catch (Exception exc)
                {
                    return($"Failed - {exc.Message}");
                }
            }
        }
Пример #9
0
 private static ViewEngineResult GetViewEngineResult(Controller controller, string viewName, bool isPartial, IViewEngine viewEngine)
 {
     if (viewName.StartsWith("~/"))
     {
         var env = controller.HttpContext.RequestServices.GetService <IWebHostEnvironment>();
         return(viewEngine.GetView(env.WebRootPath, viewName, !isPartial));
     }
     else
     {
         return(viewEngine.FindView(controller.ControllerContext, viewName, !isPartial));
     }
 }
        /// <summary>
        /// Attempts to locate a view with the given <paramref name="templateName"/>
        /// </summary>
        /// <param name="viewEngine">The view engine.</param>
        /// <param name="viewContext">The view context.</param>
        /// <param name="templateName">Name of the template.</param>
        /// <param name="viewDirectory">The view directory.</param>
        /// <param name="view">The view.</param>
        protected virtual bool TryGetView(IViewEngine viewEngine, ViewContext viewContext, string templateName, string viewDirectory, out IView view)
        {
            Guard.NotNull(viewEngine, nameof(viewEngine));
            Guard.NotNull(viewContext, nameof(viewContext));

            var result = viewEngine.GetView(viewContext.ExecutingFilePath, templateName, isMainPage: false);

            if (!result.Success && !string.IsNullOrEmpty(viewDirectory))
            {
                result = viewEngine.FindView(viewContext, viewDirectory + "/" + templateName, isMainPage: false);
            }

            view = result.View;
            return(result.Success);
        }
Пример #11
0
        public IActionResult Index()
        {
            var viewName = UmbracoContext.Content.ContentTypeAlias;
            var result   = _viewEngine.GetView("", viewName, true);

            if (!result.Success)
            {
                result = _viewEngine.FindView(ControllerContext, viewName, true);
            }
            if (!result.Success)
            {
                viewName = "Index";
            }

            return(View(viewName, UmbracoContext.Content));
        }
Пример #12
0
        private static ViewEngineResult GetViewEngineResult(Controller controller, string viewName, bool isPartial, IViewEngine viewEngine)
        {
            if (viewName.StartsWith("~/"))
            {
                var hostingEnv = controller.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;

                if (hostingEnv == null)
                {
                    throw new NullReferenceException();
                }

                return(viewEngine.GetView(hostingEnv.WebRootPath, viewName, !isPartial));
            }

            return(viewEngine.FindView(controller.ControllerContext, viewName, !isPartial));
        }
Пример #13
0
        public static void Contextualize <TModel>(this IHtmlHelper helper, Controller controller, string viewName, TModel model, bool partial = false)
        {
            using var writer = new StringWriter();
            IViewEngine      viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = viewEngine.GetView(viewName, viewName, !partial);

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


            (helper as IViewContextAware).Contextualize(viewContext);
        }
Пример #14
0
        /// <inheritdoc />
        public async Task <string> RenderAsync(string template, object model,
                                               CancellationToken cancellationToken = default)
        {
            var actionContext = GetActionContext(cancellationToken);

            // Try to find the view with the given name
            var result = !string.IsNullOrEmpty(template) && IsApplicationRelativeViewName(template)
                ? _viewEngine.GetView(null, template, false)
                : _viewEngine.FindView(actionContext, template, false);

            // Determine if we were able to find a view with the given name
            if (!result.Success || result.View == null)
            {
                // Could not find the view using the current view engine
                throw new ArgumentException(
                          $"{template} does not match any available view",
                          nameof(template));
            }

            // Render the view
            using (var writer = new StringWriter())
            {
                var viewContext = new ViewContext(
                    actionContext,
                    result.View,
                    new ViewDataDictionary(
                        new EmptyModelMetadataProvider(),
                        new ModelStateDictionary()
                        )
                {
                    Model = model
                },
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions()
                    );

                await result.View.RenderAsync(viewContext);

                return(writer.ToString());
            }
        }
Пример #15
0
        public async Task <string> RenderViewToString <TModel>(string viewName, TModel model)
        {
            ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                IViewEngine      viewEngine  = HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult  = viewEngine.GetView(viewName, viewName, false);
                ViewContext      viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    ViewData,
                    TempData,
                    writer,
                    new HtmlHelperOptions()
                    );
                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
Пример #16
0
        public IHtmlContent Render()
        {
            var defaultActions = GetDefaultActions();
            var modeViewPath   = _readOnly ? DisplayTemplateViewPath : EditorTemplateViewPath;

            foreach (string viewName in GetViewNames())
            {
                var viewEngineResult = _viewEngine.GetView(_viewContext.ExecutingFilePath, viewName, isMainPage: false);
                if (!viewEngineResult.Success)
                {
                    var fullViewName = modeViewPath + "/" + viewName;
                    viewEngineResult = _viewEngine.FindView(_viewContext, fullViewName, isMainPage: false);
                }

                if (viewEngineResult.Success)
                {
                    var viewBuffer = new ViewBuffer(_bufferScope, viewName);
                    using (var writer = new HtmlContentWrapperTextWriter(viewBuffer, _viewContext.Writer.Encoding))
                    {
                        // Forcing synchronous behavior so users don't have to await templates.
                        var view = viewEngineResult.View;
                        using (view as IDisposable)
                        {
                            var viewContext = new ViewContext(_viewContext, viewEngineResult.View, _viewData, writer);
                            var renderTask  = viewEngineResult.View.RenderAsync(viewContext);
                            renderTask.GetAwaiter().GetResult();
                            return(writer.ContentBuilder);
                        }
                    }
                }

                Func <IHtmlHelper, IHtmlContent> defaultAction;
                if (defaultActions.TryGetValue(viewName, out defaultAction))
                {
                    return(defaultAction(MakeHtmlHelper(_viewContext, _viewData)));
                }
            }

            throw new InvalidOperationException(
                      Resources.FormatTemplateHelpers_NoTemplate(_viewData.ModelExplorer.ModelType.FullName));
        }
Пример #17
0
        private async Task <string> Render(string viewName, object model)
        {
            var viewEngineResult = _viewEngine.GetView(null, viewName, true);

            if (viewEngineResult.Success)
            {
                using (var writer = new StringWriter())
                {
                    var view          = viewEngineResult.View;
                    var actionContext = new ActionContext(HttpContext, RouteData,
                                                          ControllerContext.ActionDescriptor, ModelState);
                    var viewContext = new ViewContext(actionContext, view, ViewData,
                                                      TempData, writer, new HtmlHelperOptions());

                    ViewData.Model = model;
                    await view.RenderAsync(viewContext);

                    return(writer.ToString());
                }
            }
            throw new InvalidOperationException($"Could not render {viewName}");
        }
Пример #18
0
        public static async Task <string> RenderViewAsync <TModel>(this Controller controller, string viewName, TModel model, bool partial)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetRequiredService <ICompositeViewEngine>();
                var         viewResult = viewEngine.GetView("~/", viewName, !partial);
                if (viewResult.Success == false)
                {
                    return($"View with name '{viewName}' could not be found.");
                }

                var tempDataProvider = controller.HttpContext.RequestServices.GetRequiredService <ITempDataProvider>();
                var actionContext    = new ActionContext(controller.HttpContext, new RouteData(), new ActionDescriptor());

                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.GetStringBuilder().ToString());
            }
        }
Пример #19
0
        private IView FindView(ActionContext actionContext, string viewName, IViewEngine viewEngine)
        {
            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(
                System.Environment.NewLine,
                new[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations));;

            throw new InvalidOperationException(errorMessage);
        }
Пример #20
0
 /// <summary>
 /// Gets the view with the given <paramref name="viewPath"/>, relative to <paramref name="executingFilePath"/>
 /// unless <paramref name="viewPath"/> is already absolute.
 /// </summary>
 /// <param name="executingFilePath">The absolute path to the currently-executing view, if any.</param>
 /// <param name="viewPath">The path to the view.</param>
 /// <param name="isMainPage">Determines if the page being found is the main page for an action.</param>
 /// <returns>The <see cref="ViewEngineResult"/> of locating the view.</returns>
 public ViewEngineResult GetView(string executingFilePath, string viewPath, bool isMainPage) =>
 _wrapped.GetView(executingFilePath, viewPath, isMainPage);