public string RenderToString <TModel>(string viewPath, TModel model, ViewDataDictionary viewData) { try { var viewEngineResult = _viewEngine.GetView("~/", viewPath, false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn't find view {viewPath}"); } var view = viewEngineResult.View; using (var sw = new StringWriter()) { viewData.Model = model; var viewContext = new ViewContext() { HttpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext { RequestServices = _serviceProvider }, ViewData = viewData, Writer = sw }; view.RenderAsync(viewContext).GetAwaiter().GetResult(); return(sw.ToString()); } } catch { throw; } }
public string RenderToString <TModel>(string viewPath, TModel model) { try { var viewEngineResult = _viewEngine.GetView("~/", viewPath, false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn't find view {viewPath}"); } var view = viewEngineResult.View; using (var sw = new StringWriter()) { var viewContext = new ViewContext() { HttpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext { RequestServices = _serviceProvider }, ViewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, Writer = sw }; view.RenderAsync(viewContext).GetAwaiter().GetResult(); return(sw.ToString()); } } catch (Exception ex) { throw new Exception("Error ending email.", ex); } }
public ViewEngineResult GetPageFromPathInfo(string pathInfo) { if (pathInfo.EndsWith("/")) { pathInfo += "default.cshtml"; } var viewPath = "~/wwwroot".CombineWith(pathInfo); if (!viewPath.EndsWith(".cshtml")) { viewPath += ".cshtml"; } var viewEngineResult = viewEngine.GetView("", viewPath, isMainPage: viewPath == "~/wwwroot/default.cshtml"); if (!viewEngineResult.Success) { viewPath = PagesPath.CombineWith(pathInfo); if (!viewPath.EndsWith(".cshtml")) { viewPath += ".cshtml"; } viewEngineResult = viewEngine.GetView("", viewPath, isMainPage: viewPath == $"{PagesPath}/default.cshtml"); } return(viewEngineResult.Success ? viewEngineResult : null); }
private static async Task HandlePostAsync(Post post, Settings settings, TemplatingOptions options, IServiceProvider services, IRazorViewEngine engine, string type) { var httpContext = new DefaultHttpContext { RequestServices = services }; var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var modelStateDictionary = new ModelStateDictionary(); var modelMetadataProvider = new EmptyModelMetadataProvider(); var tempDataProvider = new VirtualTempDataProvider(); var htmlHelperOptions = new HtmlHelperOptions(); var actionContext = new ActionContext(httpContext, routeData, actionDescriptor, modelStateDictionary); var viewDataDictionary = new ViewDataDictionary(modelMetadataProvider, modelStateDictionary); var tempDataDictionary = new TempDataDictionary(httpContext, tempDataProvider); viewDataDictionary.Model = post; using (var stringWriter = new StringWriter()) { var view = engine.GetView(".", $"/Templates/{type}.cshtml", true); var viewContext = new ViewContext(actionContext, view.View, viewDataDictionary, tempDataDictionary, stringWriter, htmlHelperOptions); await view.View.RenderAsync(viewContext); var result = stringWriter.ToString(); var directory = Path.Combine(options.OutputDirectory, post.Slug); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(Path.Combine(directory, "index.html"), result); await DownloadImagesFromPostAsync(post.HTML, settings, options); if (type == "post") { //amp it view = engine.GetView(".", $"/Templates/post-amp.cshtml", true); viewContext = new ViewContext(actionContext, view.View, viewDataDictionary, tempDataDictionary, stringWriter, htmlHelperOptions); await view.View.RenderAsync(viewContext); result = stringWriter.ToString(); directory = Path.Combine(directory, "amp"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(Path.Combine(directory, "index.html"), result); } } }
private IView FindView(ActionContext actionContext, string viewName) { Guard.Against.NullOrEmpty(viewName, nameof(viewName)); Guard.Against.Null(actionContext, nameof(actionContext)); 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); }
public async Task <string> RenderToStringAsync(string viewName, object model, string locatorUrl) { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { var viewResult = _razorViewEngine.GetView("~/", viewName, false); if (viewResult.View == null) { throw new ArgumentNullException($"{viewName} does not match any available view"); } var viewContext = new ViewContext() { HttpContext = httpContextAccessor.HttpContext ?? new DefaultHttpContext { RequestServices = _serviceProvider }, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, Writer = sw }; viewContext.ViewBag.LocatorUrl = locatorUrl; await viewResult.View.RenderAsync(viewContext); return(sw.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)); logger.LogError(errorMessage); throw new ArgumentException($"Unable to find tempalte '{viewName}'"); }
///<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()); } }
/// <summary> /// Renders the specified view and model into a string. /// </summary> /// <param name="viewName">The name of the view to render.</param> /// <param name="model">The model for the view to render.</param> /// <returns></returns> public virtual 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 && (viewResult = _razorViewEngine.GetView("~/Views", viewName, false)).View == null) { throw new InvalidOperationException($"'{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 async Task <byte[]> ExportToPdf(object model, string viewName) { try { // use for http routing var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); // used to convert view to string using (var stringWriter = new StringWriter()) { // get view var viewResult = _razorViewEngine.GetView("", "~/" + viewName, false); if (!viewResult.Success) { throw new ArgumentNullException($"{viewName} does not match any available view"); } // set the model value for view var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; // initialize view var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), stringWriter, new HtmlHelperOptions() ); // render view await viewResult.View.RenderAsync(viewContext); var _stream = new MemoryStream(); // convert string to pdf in stream & then destroy the stream using (var pdfWriter = new PdfWriter(_stream)) { pdfWriter.SetCloseStream(false); // CAUTION : Don't remove using block from here, it used to destroy the stream once pdf is generated using (var document = HtmlConverter.ConvertToDocument(stringWriter.ToString(), pdfWriter)) { } } _stream.Position = 0; return(_stream.ToArray()); } } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// renderView to html string with viewmodel /// </summary> /// <param name="viewName">view name</param> /// <param name="viewModel">view model</param> /// <returns></returns> public async Task <string> RenderViewToStringAsync(string viewName, object viewModel) { var actionContext = new ActionContext(_httpContext, new RouteData(), new ActionDescriptor()); var viewEngineResult = _razorViewEngine.GetView(viewName, viewName, false); if (viewEngineResult.View == null || (!viewEngineResult.Success)) { throw new ArgumentNullException($"Unable to find view '{viewName}'"); } var view = viewEngineResult.View; using (var sw = new StringWriter()) { var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()); viewDictionary.Model = viewModel; var tempData = new TempDataDictionary(_httpContext, _tempDataProvider); var viewContext = new ViewContext(actionContext, view, viewDictionary, tempData, sw, new HtmlHelperOptions()); viewContext.RouteData = _httpContext.GetRouteData(); //set route data here await view.RenderAsync(viewContext); return(sw.ToString()); } }
private IView FindView(ActionContext actionContext, string viewName) { //Ако сложа isMainPage: true ще ми зарежда и Layout-а var getViewResult = razorViewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: false); if (getViewResult.Success) { return(getViewResult.View); } //Ако сложа isMainPage: true ще ми зарежда и Layout-а var findViewResult = razorViewEngine.FindView(actionContext, viewName, isMainPage: false); 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); }
public async Task <IActionResult> Signup([FromBody] SignupViewModel viewModel) { UserSignup userSignup = new UserSignup(context, viewModel.MapToUser()); await userSignup.SignupAsync(); if (userSignup.EmailAlreadyTaken) { return(new ErrorsJson("E-mail já cadastrado.")); } var viewResult = viewEngine.GetView(env.ContentRootPath, "~/Views/Emails/SignupEmail.cshtml", false); var htmlMessage = await new MailView(ControllerContext, viewResult) .ToHtmlAsync(new SignupEmail(userSignup.User, userSignup.ClosureRequest)); mailer.Recipients.Add(new MailRecipient(userSignup.User.Name, userSignup.User.Email)); taskHandler.ExecuteInBackground(async() => { await mailer.SendAsync("Bem vindo ao gestaoaju.com.br :)", htmlMessage); }); await HttpContext.SignInAsync(userSignup.User); return(new UserJson(userSignup.User)); }
/// <summary> /// 使用Razor视图引擎来生成代码文件 /// </summary> /// <typeparam name="TModel"></typeparam> /// <param name="viewPath"></param> /// <param name="model"></param> /// <returns></returns> private string Render <TModel>(string viewPath, TModel model) { DefaultHttpContext httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; ActionContext actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult viewResult = _viewEngine.GetView(null, viewPath, false); if (!viewResult.Success) { throw new InvalidOperationException($"找不到视图模板 {viewPath}"); } ViewDataDictionary viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; using (StringWriter writer = new StringWriter()) { ViewContext viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), writer, new HtmlHelperOptions() ); Task render = viewResult.View.RenderAsync(viewContext); render.Wait(); return(writer.ToString()); } }
public async Task <string> RenderToStringAsync(string viewName, object model) { var actionContext = new ActionContext(_context, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { var viewResult = _razorViewEngine.GetView(viewName, 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() ); viewContext.RouteData = _context.GetRouteData(); await viewResult.View.RenderAsync(viewContext); return(sw.GetStringBuilder().ToString()); } }
public async Task <string> RenderTemplateAsync <TModel>(string viewName, TModel model) { var actionContext = GetActionContext(); using (var sw = new StringWriter()) { var viewResult = _razorViewEngine.GetView("~/Views/", 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 Render <TModel>(string viewPath, TModel model) { var viewEngineResult = _viewEngine.GetView("~/", viewPath, false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn't find view {viewPath}"); } var view = viewEngineResult.View; using (var output = new StringWriter()) { var viewContext = new ViewContext(); viewContext.HttpContext = _httpContextAccessor.HttpContext; viewContext.ViewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; viewContext.Writer = output; view.RenderAsync(viewContext).GetAwaiter().GetResult(); return(output.ToString()); } }
private IView FindView(ActionContext actionContext, string viewName) { var getViewResult = _viewEngine.GetView(null, viewName, false); if (getViewResult.Success) { return(getViewResult.View); } var findViewResult = _viewEngine.FindView(actionContext, viewName, false); 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); }
public bool FindView(string viewName) { var actionContext = GetActionContext(); var getViewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true); if (getViewResult.Success) { return(true); } var findViewResult = _viewEngine.FindView(actionContext, viewName, isMainPage: true); if (findViewResult.Success) { return(true); } 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));; _logger.LogError(errorMessage); return(false); }
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); var viewResult = _razorViewEngine.GetView(executingFilePath: viewName, viewPath: viewName, isMainPage: 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()); } }
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 string[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations) .Concat(new string[] { "Hint:", "- Check whether you have added reference to the Razor Class Library that contains the view files.", "- Check whether the view file name is correct or exists at the given path.", "- Refer documentation here: https://github.com/soundaranbu/RazorTemplating" })); throw new InvalidOperationException(errorMessage); }
public string RenderToString <TModel>(string viewPath, TModel model) { var viewEngineResult = _razorViewEngine.GetView("~/", viewPath, false); if (!viewEngineResult.Success) { throw new ViewNotFoundException($"Couldn't find view {viewPath}"); } var view = viewEngineResult.View; using (var sw = new StringWriter()) { var viewContext = new ViewContext() { HttpContext = new DefaultHttpContext { RequestServices = _serviceProvider }, ViewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, Writer = sw }; view.RenderAsync(viewContext).GetAwaiter().GetResult(); return(sw.ToString()); } }
public static async Task <string> NccRenderToStringAsync(this ViewContext context, IRazorViewEngine razorViewEngine, string viewPath, object model) { using (var sw = new StringWriter()) { var viewResult = razorViewEngine.GetView("", viewPath, false); if (viewResult.View == null) { throw new ArgumentNullException($"{viewPath} does not match any available view"); } if (model != null) { context.ViewData.Model = model; } var viewContext = new ViewContext( context, viewResult.View, context.ViewData, context.TempData, sw, new HtmlHelperOptions() ); await viewResult.View.RenderAsync(viewContext); return(sw.ToString()); } }
public async Task <string> Render(string viewPath, object model = null) { var httpContext = new DefaultHttpContext() { RequestServices = _serviceProvider }; var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var modelStateDictionary = new ModelStateDictionary(); var modelMetadataProvider = new EmptyModelMetadataProvider(); var tempDataProvider = new VirtualTempDataProvider(); var htmlHelperOptions = new HtmlHelperOptions(); var actionContext = new ActionContext(httpContext, routeData, actionDescriptor, modelStateDictionary); var viewDataDictionary = new ViewDataDictionary(modelMetadataProvider, modelStateDictionary); var tempDataDictionary = new TempDataDictionary(httpContext, tempDataProvider); viewDataDictionary.Model = model; using (var stringWriter = new StringWriter()) { var view = _razorViewEngine.GetView(string.Empty, viewPath, true); var viewContext = new ViewContext(actionContext, view.View, viewDataDictionary, tempDataDictionary, stringWriter, htmlHelperOptions); await view.View.RenderAsync(viewContext); var result = stringWriter.ToString(); return(result); } }
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) { viewResult = _razorViewEngine.GetView(null, 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()); } }
public IView GetView(ActionContext actionContext, string viewName, bool isMainPage = true) { var getViewResult = _razorViewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: isMainPage); if (getViewResult.Success) { return(getViewResult.View); } var findViewResult = _razorViewEngine.FindView(actionContext, viewName, isMainPage: isMainPage); if (findViewResult.Success) { return(findViewResult.View); } var searchedLocations = new StringBuilder(); foreach (var location in getViewResult.SearchedLocations) { searchedLocations.Append($"{location}\n"); } foreach (var location in findViewResult.SearchedLocations) { searchedLocations.Append($"{location}\n"); } throw new InvalidOperationException( $"View '{viewName}' does not exist in directories {searchedLocations}"); }
/// <summary> /// This function renders a ViewResult into a html string and returns it /// </summary> /// <param name="result"></param> /// <returns></returns> public async Task <string> RenderToStringAsync(ViewResult result) { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { //Pulls the absolute view path and model from the viewresult //Note: the viewresult is what the engine uses normally to go and render the view string viewPath = result.ViewName; object model = result.Model; //This works with absolute paths //Note: findview does not use absolute pathss var viewResult = _razorViewEngine.GetView(viewPath, viewPath, false); if (viewResult.View == null) { throw new ArgumentNullException($"{viewPath} does not match any available view"); } //Only includes the model if its not null *as its optional* ViewDataDictionary viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()); if (model != null) { 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 async Task <string> RenderViewToStringAsync <TModel>(string viewName, TModel model) { try { var actionContext = GetActionContext(); var view = FindView(actionContext, viewName); using (var sw = new StringWriter()) { var viewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: 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() ); try { await viewResult.View.RenderAsync(viewContext); } catch (Exception ex) { } return(sw.ToString()); } } catch (Exception ex) { return(""); } }
/// <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)); }
private IView FindView(string ViewName) { ViewEngineResult viewResult = _razorViewEngine.GetView(executingFilePath: null, viewPath: ViewName, isMainPage: true); if (viewResult.Success) { return(viewResult.View); } throw new Exception("Invalid View Path"); }