public PageActionInvoker( IPageHandlerMethodSelector handlerMethodSelector, DiagnosticSource diagnosticSource, ILogger logger, PageContext pageContext, IFilterMetadata[] filterMetadata, PageActionInvokerCacheEntry cacheEntry, ParameterBinder parameterBinder, ITempDataDictionaryFactory tempDataFactory, HtmlHelperOptions htmlHelperOptions) : base( diagnosticSource, logger, pageContext, filterMetadata, pageContext.ValueProviderFactories) { _selector = handlerMethodSelector; _pageContext = pageContext; CacheEntry = cacheEntry; _parameterBinder = parameterBinder; _tempDataFactory = tempDataFactory; _htmlHelperOptions = htmlHelperOptions; _actionDescriptor = pageContext.ActionDescriptor; }
public ViewContext GenerateViewContext <TModel>( string viewName = default, TModel model = default, TextWriter writer = default, object additionalViewData = default, HtmlHelperOptions options = default) { writer ??= new StringWriter(); var viewData = new ViewDataDictionary(_metadataProvider, _context.ModelState) { Model = model }; // if additional view data was provided, add each property if (additionalViewData != default) { foreach (var prop in additionalViewData.GetType().GetProperties()) { viewData[prop.Name] = prop.GetValue(additionalViewData); } } return(new ViewContext( _context, viewName != default ? FindView(viewName) : new FakeView(), viewData, _tempData, writer, options ?? new HtmlHelperOptions() )); }
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 = this._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); } }
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()); } } }
/// <summary> /// Asynchronously renders the specified <paramref name="view"/> to the response body. /// </summary> /// <param name="view">The <see cref="IView"/> to render.</param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param> /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param> /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns> public static async Task ExecuteAsync([NotNull] IView view, [NotNull] ActionContext actionContext, [NotNull] ViewDataDictionary viewData, [NotNull] ITempDataDictionary tempData, [NotNull] HtmlHelperOptions htmlHelperOptions, MediaTypeHeaderValue contentType) { var response = actionContext.HttpContext.Response; contentType = contentType ?? DefaultContentType; if (contentType.Encoding == null) { // Do not modify the user supplied content type, so copy it instead contentType = contentType.Copy(); contentType.Encoding = Encoding.UTF8; } response.ContentType = contentType.ToString(); using (var writer = new HttpResponseStreamWriter(response.Body, contentType.Encoding)) { var viewContext = new ViewContext( actionContext, view, viewData, tempData, writer, htmlHelperOptions); await view.RenderAsync(viewContext); } }
public void GenerateTextBox_AlwaysUsesCultureSpecificFormatting_WhenOptionIsSet(string type, Html5DateRenderingMode dateRenderingMode, bool shouldUseInvariantFormatting) { // Arrange var metadataProvider = new TestModelMetadataProvider(); var htmlHelperOptions = new HtmlHelperOptions() { Html5DateRenderingMode = dateRenderingMode, FormInputRenderMode = FormInputRenderMode.AlwaysUseCurrentCulture, }; var htmlGenerator = GetGenerator(metadataProvider, new() { HtmlHelperOptions = htmlHelperOptions }); var viewContext = GetViewContext <Model>(model: null, metadataProvider, htmlHelperOptions); var expression = nameof(Model.Name); var modelMetadata = metadataProvider.GetMetadataForProperty(typeof(Model), expression); var modelExplorer = new ModelExplorer(metadataProvider, modelMetadata, null); var htmlAttributes = new Dictionary <string, object> { { "name", "testElement" }, { "type", type }, }; // Act _ = htmlGenerator.GenerateTextBox(viewContext, modelExplorer, expression, null, null, htmlAttributes); // Assert var didForceInvariantFormatting = viewContext.FormContext.InvariantField(expression); Assert.False(didForceInvariantFormatting); }
public PageActionInvokerProvider( IPageLoader loader, IPageFactoryProvider pageFactoryProvider, IPageModelFactoryProvider modelFactoryProvider, IRazorPageFactoryProvider razorPageFactoryProvider, IActionDescriptorCollectionProvider collectionProvider, IEnumerable <IFilterProvider> filterProviders, ParameterBinder parameterBinder, IModelMetadataProvider modelMetadataProvider, ITempDataDictionaryFactory tempDataFactory, IOptions <MvcOptions> mvcOptions, IOptions <HtmlHelperOptions> htmlHelperOptions, IPageHandlerMethodSelector selector, RazorProject razorProject, DiagnosticSource diagnosticSource, ILoggerFactory loggerFactory) { _loader = loader; _pageFactoryProvider = pageFactoryProvider; _modelFactoryProvider = modelFactoryProvider; _razorPageFactoryProvider = razorPageFactoryProvider; _collectionProvider = collectionProvider; _filterProviders = filterProviders.ToArray(); _valueProviderFactories = mvcOptions.Value.ValueProviderFactories.ToArray(); _parameterBinder = parameterBinder; _modelMetadataProvider = modelMetadataProvider; _tempDataFactory = tempDataFactory; _htmlHelperOptions = htmlHelperOptions.Value; _selector = selector; _razorProject = razorProject; _diagnosticSource = diagnosticSource; _logger = loggerFactory.CreateLogger <PageActionInvoker>(); }
public PageActionInvoker( IPageHandlerMethodSelector handlerMethodSelector, DiagnosticListener diagnosticListener, ILogger logger, IActionContextAccessor actionContextAccessor, IActionResultTypeMapper mapper, PageContext pageContext, IFilterMetadata[] filterMetadata, PageActionInvokerCacheEntry cacheEntry, ITempDataDictionaryFactory tempDataFactory, HtmlHelperOptions htmlHelperOptions) : base( diagnosticListener, logger, actionContextAccessor, mapper, pageContext, filterMetadata, pageContext.ValueProviderFactories) { _selector = handlerMethodSelector; _pageContext = pageContext; CacheEntry = cacheEntry; _tempDataFactory = tempDataFactory; _htmlHelperOptions = htmlHelperOptions; _actionDescriptor = pageContext.ActionDescriptor; }
public PageContext( ActionContext actionContext, ViewDataDictionary viewData, ITempDataDictionary tempDataDictionary, HtmlHelperOptions htmlHelperOptions) : base(actionContext, NullView.Instance, viewData, tempDataDictionary, TextWriter.Null, htmlHelperOptions) { }
public ViewContext(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, TextWriter writer, HtmlHelperOptions htmlHelperOptions, IDocument document, IExecutionContext executionContext) : base(actionContext, view, viewData, tempData, writer, htmlHelperOptions) { viewData[ViewDataKeys.WyamDocument] = document; viewData[ViewDataKeys.WyamExecutionContext] = executionContext; }
public HtmlHelperGeneratorService(IHtmlGenerator htmlGenerator, ICompositeViewEngine compositeViewEngine, IModelMetadataProvider modelMetadataProvider, IViewBufferScope viewBufferScope, IActionContextAccessor actionContextAccessor, ITempDataProvider tempDataProvider, IOptions <MvcViewOptions> options) { _htmlGenerator = htmlGenerator; _compositeViewEngine = compositeViewEngine; _modelMetadataProvider = modelMetadataProvider; _viewBufferScope = viewBufferScope; _actionContextAccessor = actionContextAccessor; _tempDataProvider = tempDataProvider; _htmlHelperOptions = options.Value.HtmlHelperOptions; }
public string Render(HttpContext context, string layout, string viewName, object model = null, Dictionary <string, object> viewData = null) { ActionContext actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { RazorPageResult viewResult = _razorViewEngine.FindPage(actionContext, viewName); viewResult.Page.Layout = layout; if (viewResult.Page == 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(); //var viewContext = new ViewContext( // actionContext, // null, // viewDictionary, // new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), // sw, // opts //); viewResult.Page.ViewContext = new ViewContext(); viewResult.Page.ViewContext.View.RenderAsync(viewContext); Task.WaitAll(viewResult.Page.ExecuteAsync()); viewResult.Page.ViewContext.ViewData = viewDictionary; viewResult.Page.ViewContext.Writer = sw; Task.WaitAll(viewResult.Page.ViewContext.View.RenderAsync(viewContext)); return(sw.ToString()); } }
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); } } }
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()); } } }
/// <summary> /// Initializes a new instance of <see cref="ViewContext"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/>.</param> /// <param name="view">The <see cref="IView"/> being rendered.</param> /// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param> /// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param> /// <param name="writer">The <see cref="TextWriter"/> to render output to.</param> /// <param name="htmlHelperOptions">The <see cref="HtmlHelperOptions"/> to apply to this instance.</param> public ViewContext( ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, TextWriter writer, HtmlHelperOptions htmlHelperOptions) : base(actionContext) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (view == null) { throw new ArgumentNullException(nameof(view)); } if (viewData == null) { throw new ArgumentNullException(nameof(viewData)); } if (tempData == null) { throw new ArgumentNullException(nameof(tempData)); } if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (htmlHelperOptions == null) { throw new ArgumentNullException(nameof(htmlHelperOptions)); } View = view; ViewData = viewData; TempData = tempData; Writer = writer; FormContext = new FormContext(); ClientValidationEnabled = htmlHelperOptions.ClientValidationEnabled; Html5DateRenderingMode = htmlHelperOptions.Html5DateRenderingMode; ValidationSummaryMessageElement = htmlHelperOptions.ValidationSummaryMessageElement; ValidationMessageElement = htmlHelperOptions.ValidationMessageElement; CheckBoxHiddenInputRenderMode = htmlHelperOptions.CheckBoxHiddenInputRenderMode; }
protected TestViewContext( TestActionContext actionContext, Mock <IView> view, ViewDataDictionary <T> viewData, Mock <ITempDataDictionary> tempData, HtmlHelperOptions options) : base(actionContext, view.Object, viewData, tempData.Object, new StringWriter(), options) { ActionContext = actionContext; MockView = view; MockTempData = tempData; Options = options; }
/// <summary> /// Initializes a new instance of <see cref="ViewContext"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/>.</param> /// <param name="view">The <see cref="IView"/> being rendered.</param> /// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param> /// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param> /// <param name="writer">The <see cref="TextWriter"/> to render output to.</param> public ViewContext( ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, TextWriter writer, HtmlHelperOptions htmlHelperOptions) : base(actionContext) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (view == null) { throw new ArgumentNullException(nameof(view)); } if (viewData == null) { throw new ArgumentNullException(nameof(viewData)); } if (tempData == null) { throw new ArgumentNullException(nameof(tempData)); } if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (htmlHelperOptions == null) { throw new ArgumentNullException(nameof(htmlHelperOptions)); } View = view; ViewData = viewData; TempData = tempData; Writer = writer; _formContext = _defaultFormContext; ClientValidationEnabled = htmlHelperOptions.ClientValidationEnabled; Html5DateRenderingMode = htmlHelperOptions.Html5DateRenderingMode; ValidationSummaryMessageElement = htmlHelperOptions.ValidationSummaryMessageElement; ValidationMessageElement = htmlHelperOptions.ValidationMessageElement; }
/// <summary> /// Asynchronously renders the specified <paramref name="view"/> to the response body. /// </summary> /// <param name="view">The <see cref="IView"/> to render.</param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param> /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param> /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns> public static async Task ExecuteAsync([NotNull] IView view, [NotNull] ActionContext actionContext, [NotNull] ViewDataDictionary viewData, [NotNull] ITempDataDictionary tempData, [NotNull] HtmlHelperOptions htmlHelperOptions, MediaTypeHeaderValue contentType) { var response = actionContext.HttpContext.Response; var contentTypeHeader = contentType; Encoding encoding; if (contentTypeHeader == null) { contentTypeHeader = DefaultContentType; encoding = Encodings.UTF8EncodingWithoutBOM; } else { if (contentTypeHeader.Encoding == null) { // 1. Do not modify the user supplied content type // 2. Parse here to handle parameters apart from charset contentTypeHeader = MediaTypeHeaderValue.Parse(contentTypeHeader.ToString()); contentTypeHeader.Encoding = Encodings.UTF8EncodingWithoutBOM; encoding = Encodings.UTF8EncodingWithoutBOM; } else { encoding = contentTypeHeader.Encoding; } } response.ContentType = contentTypeHeader.ToString(); using (var writer = new HttpResponseStreamWriter(response.Body, encoding)) { var viewContext = new ViewContext( actionContext, view, viewData, tempData, writer, htmlHelperOptions); await view.RenderAsync(viewContext); } }
public async Task <string> RenderViewToStringAsync <TModel>(string viewName, TModel model) { var actionContext = GetActionContext(); var view = FindView(viewName); var viewData = new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; var tempData = new TempDataDictionary(actionContext.HttpContext, tempDataProvider); var htmlHelperOptions = new HtmlHelperOptions(); var output = new StringWriter(); var viewContext = new ViewContext(actionContext, view, viewData, tempData, output, htmlHelperOptions); await view.RenderAsync(viewContext); return(output.ToString()); }
public ViewComponentResultExecutor( IOptions<MvcViewOptions> mvcHelperOptions, IViewComponentHelper viewComponentHelper, ILoggerFactory loggerFactory, HtmlEncoder htmlEncoder, IModelMetadataProvider modelMetadataProvider, ITempDataDictionaryFactory tempDataDictionaryFactory) { if (mvcHelperOptions == null) { throw new ArgumentNullException(nameof(mvcHelperOptions)); } if (viewComponentHelper == null) { throw new ArgumentNullException(nameof(viewComponentHelper)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (htmlEncoder == null) { throw new ArgumentNullException(nameof(htmlEncoder)); } if (modelMetadataProvider == null) { throw new ArgumentNullException(nameof(modelMetadataProvider)); } if (tempDataDictionaryFactory == null) { throw new ArgumentNullException(nameof(tempDataDictionaryFactory)); } _htmlHelperOptions = mvcHelperOptions.Value.HtmlHelperOptions; _viewComponentHelper = viewComponentHelper; _logger = loggerFactory.CreateLogger<ViewComponentResult>(); _htmlEncoder = htmlEncoder; _modelMetadataProvider = modelMetadataProvider; _tempDataDictionaryFactory = tempDataDictionaryFactory; }
public ViewComponentResultExecutor( IOptions <MvcViewOptions> mvcHelperOptions, IViewComponentHelper viewComponentHelper, ILoggerFactory loggerFactory, HtmlEncoder htmlEncoder, IModelMetadataProvider modelMetadataProvider, ITempDataDictionaryFactory tempDataDictionaryFactory) { if (mvcHelperOptions == null) { throw new ArgumentNullException(nameof(mvcHelperOptions)); } if (viewComponentHelper == null) { throw new ArgumentNullException(nameof(viewComponentHelper)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (htmlEncoder == null) { throw new ArgumentNullException(nameof(htmlEncoder)); } if (modelMetadataProvider == null) { throw new ArgumentNullException(nameof(modelMetadataProvider)); } if (tempDataDictionaryFactory == null) { throw new ArgumentNullException(nameof(tempDataDictionaryFactory)); } _htmlHelperOptions = mvcHelperOptions.Value.HtmlHelperOptions; _viewComponentHelper = viewComponentHelper; _logger = loggerFactory.CreateLogger <ViewComponentResult>(); _htmlEncoder = htmlEncoder; _modelMetadataProvider = modelMetadataProvider; _tempDataDictionaryFactory = tempDataDictionaryFactory; }
public MvcOptions() { Conventions = new List <IApplicationModelConvention>(); ModelBinders = new List <IModelBinder>(); ViewEngines = new List <ViewEngineDescriptor>(); ValueProviderFactories = new List <IValueProviderFactory>(); OutputFormatters = new List <IOutputFormatter>(); InputFormatters = new List <IInputFormatter>(); Filters = new List <IFilter>(); FormatterMappings = new FormatterMappings(); ValidationExcludeFilters = new List <IExcludeTypeValidationFilter>(); ModelMetadataDetailsProviders = new List <IMetadataDetailsProvider>(); ModelValidatorProviders = new List <IModelValidatorProvider>(); ClientModelValidatorProviders = new List <IClientModelValidatorProvider>(); CacheProfiles = new Dictionary <string, CacheProfile>(StringComparer.OrdinalIgnoreCase); HtmlHelperOptions = new HtmlHelperOptions(); SerializerSettings = SerializerSettingsProvider.CreateSerializerSettings(); }
public static ViewContext Create(string requestPathBase = null) { var serviceProvider = ServiceProviderTestFactory.Create(); HttpContext httpContext = new DefaultHttpContext { RequestServices = serviceProvider }; //var request = new DefaultHttpRequest(httpContext) //{ // Host = new HostString(Domain), // PathBase = "/testpathbase", // Path = "/testpath", // QueryString = new QueryString("?testquery=123&test=ABC"), // Scheme = "https" //}; if (requestPathBase != null) { //request.PathBase = new PathString(requestPathBase); } //httpContext = request.HttpContext; var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(httpContext, routeData, actionDescriptor); var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()); var htmlHelperOptions = new HtmlHelperOptions(); var viewContext = new ViewContext( actionContext, Mock.Of <IView>(), viewData, Mock.Of <ITempDataDictionary>(), TextWriter.Null, htmlHelperOptions); return(viewContext); }
/// <summary> /// Initializes a new instance of <see cref="ViewContext"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/>.</param> /// <param name="view">The <see cref="IView"/> being rendered.</param> /// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param> /// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param> /// <param name="writer">The <see cref="TextWriter"/> to render output to.</param> public ViewContext( [NotNull] ActionContext actionContext, [NotNull] IView view, [NotNull] ViewDataDictionary viewData, [NotNull] ITempDataDictionary tempData, [NotNull] TextWriter writer, [NotNull] HtmlHelperOptions htmlHelperOptions) : base(actionContext) { View = view; ViewData = viewData; TempData = tempData; Writer = writer; _formContext = _defaultFormContext; ClientValidationEnabled = htmlHelperOptions.ClientValidationEnabled; Html5DateRenderingMode = htmlHelperOptions.Html5DateRenderingMode; ValidationSummaryMessageElement = htmlHelperOptions.ValidationSummaryMessageElement; ValidationMessageElement = htmlHelperOptions.ValidationMessageElement; }
public MvcViewTestContext(ActionContext actionContext, IModelMetadataProvider modelMetadataProvider, IHtmlGenerator htmlGenerator) { ViewData = new ViewDataDictionary <TModel>(modelMetadataProvider, new ModelStateDictionary()); View = new NullView(); Writer = Substitute.For <TextWriter>(); TempData = new TempDataDictionary(actionContext.HttpContext, new TempDataProviderMock()); var htmlHelperOptions = new HtmlHelperOptions(); htmlHelperOptions.ClientValidationEnabled = true; ViewContext = new ViewContext(actionContext, View, ViewData, TempData, Writer, htmlHelperOptions); HtmlHelper = new HtmlHelper <TModel>( htmlGenerator, TestApplication.Services.GetRequiredService <ICompositeViewEngine>(), TestApplication.Services.GetRequiredService <IModelMetadataProvider>(), TestApplication.Services.GetRequiredService <IViewBufferScope>(), HtmlEncoder.Default, UrlEncoder.Default, new ModelExpressionProvider(TestApplication.Services.GetRequiredService <IModelMetadataProvider>())); HtmlHelper.Contextualize(ViewContext); }
public async Task <string> RenderViewToStringAsync <TModel>(string viewLocation, TModel model) { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; //HttpContext httpContext = _accessor.HttpContext; //httpContext.RequestServices = _serviceProvider; ActionContext actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); IView view = FindView(actionContext, viewLocation); using (StringWriter stringWriter = new StringWriter()) { ViewDataDictionary <TModel> viewDataDictionary = new ViewDataDictionary <TModel>( new EmptyModelMetadataProvider(), new ModelStateDictionary()); viewDataDictionary.Model = model; TempDataDictionary tempDataDictionary = new TempDataDictionary( actionContext.HttpContext, _tempDataProvider); HtmlHelperOptions htmlHelperOptions = new HtmlHelperOptions(); ViewContext viewContext = new ViewContext( actionContext, view, viewDataDictionary, tempDataDictionary, stringWriter, htmlHelperOptions); //viewContext.RouteData = _accessor.HttpContext.GetRouteData(); await view.RenderAsync(viewContext); return(stringWriter.ToString()); } }
public PageActionInvokerProvider( IPageLoader loader, IPageFactoryProvider pageFactoryProvider, IPageModelFactoryProvider modelFactoryProvider, IRazorPageFactoryProvider razorPageFactoryProvider, IActionDescriptorCollectionProvider collectionProvider, IEnumerable <IFilterProvider> filterProviders, ParameterBinder parameterBinder, IModelMetadataProvider modelMetadataProvider, IModelBinderFactory modelBinderFactory, ITempDataDictionaryFactory tempDataFactory, IOptions <MvcOptions> mvcOptions, IOptions <HtmlHelperOptions> htmlHelperOptions, IPageHandlerMethodSelector selector, DiagnosticListener diagnosticListener, ILoggerFactory loggerFactory, IActionResultTypeMapper mapper, IActionContextAccessor actionContextAccessor) { _loader = loader; _pageFactoryProvider = pageFactoryProvider; _modelFactoryProvider = modelFactoryProvider; _modelBinderFactory = modelBinderFactory; _razorPageFactoryProvider = razorPageFactoryProvider; _collectionProvider = collectionProvider; _filterProviders = filterProviders.ToArray(); _valueProviderFactories = mvcOptions.Value.ValueProviderFactories.ToArray(); _parameterBinder = parameterBinder; _modelMetadataProvider = modelMetadataProvider; _tempDataFactory = tempDataFactory; _mvcOptions = mvcOptions.Value; _htmlHelperOptions = htmlHelperOptions.Value; _selector = selector; _diagnosticListener = diagnosticListener; _logger = loggerFactory.CreateLogger <PageActionInvoker>(); _mapper = mapper; _actionContextAccessor = actionContextAccessor ?? ActionContextAccessor.Null; }
/// <summary> /// Renders Razor View or Partial View to the output. /// </summary> public static Task RenderPartialAsync(this HttpContext context, TextWriter output, string viewName, object model = null, ViewDataDictionary viewdata = null, IViewEngine viewEngine = null, ITempDataDictionaryFactory tmpdataFactory = null, HtmlHelperOptions htmlOptions = null) { // dummy router: var routedata = new RouteData(); routedata.Routers.Add(new PhpScriptRouter()); // find the view: var action = new ActionContext(context, routedata, new ActionDescriptor()); viewEngine ??= context.RequestServices.GetService <ICompositeViewEngine>() ?? context.RequestServices.GetService <IViewEngine>(); var view = viewEngine.FindView(action, viewName, isMainPage: false); if (view.Success) { // render the view: tmpdataFactory ??= context.RequestServices.GetService <ITempDataDictionaryFactory>(); viewdata ??= new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()); var viewctx = new ViewContext(action, view.View, new CustomViewDataDictionary(viewdata, model, model != null ? model.GetType() : typeof(object)), tmpdataFactory.GetTempData(context), output, htmlOptions ?? new HtmlHelperOptions { }); return(view.View.RenderAsync(viewctx)); } else { throw new ArgumentException(nameof(viewName)); } }
/// <summary> /// Asynchronously renders the specified <paramref name="view"/> to the response body. /// </summary> /// <param name="view">The <see cref="IView"/> to render.</param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param> /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param> /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns> public static async Task ExecuteAsync( IView view, ActionContext actionContext, ViewDataDictionary viewData, ITempDataDictionary tempData, HtmlHelperOptions htmlHelperOptions, MediaTypeHeaderValue contentType) { if (view == null) { throw new ArgumentNullException(nameof(view)); } if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (viewData == null) { throw new ArgumentNullException(nameof(viewData)); } if (tempData == null) { throw new ArgumentNullException(nameof(tempData)); } if (htmlHelperOptions == null) { throw new ArgumentNullException(nameof(htmlHelperOptions)); } var response = actionContext.HttpContext.Response; if (contentType != null && contentType.Encoding == null) { // Do not modify the user supplied content type, so copy it instead contentType = contentType.Copy(); contentType.Encoding = Encoding.UTF8; } // Priority list for setting content-type: // 1. passed in contentType (likely set by the user on the result) // 2. response.ContentType (likely set by the user in controller code) // 3. ViewExecutor.DefaultContentType (sensible default) response.ContentType = contentType?.ToString() ?? response.ContentType ?? DefaultContentType.ToString(); using (var writer = new HttpResponseStreamWriter(response.Body, contentType?.Encoding ?? DefaultContentType.Encoding)) { var viewContext = new ViewContext( actionContext, view, viewData, tempData, writer, htmlHelperOptions); await view.RenderAsync(viewContext); // Invoke FlushAsync to ensure any buffered content is asynchronously written to the underlying // response. In the absence of this line, the buffer gets synchronously written to the response // as part of the Dispose which has a perf impact. await writer.FlushAsync(); } }
private static async Task HandleIndexPageAsync(Post[] posts, Settings settings, TemplatingOptions options, IServiceProvider services, IRazorViewEngine engine) { var postsToDisplay = 27; 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); var imageDirectory = Path.Combine(options.OutputDirectory, "content", "images", "index"); var index = new IndexPage { Options = options, Settings = settings }; posts = posts.OrderByDescending(x => x.PublishedAt).ToArray(); if (!Directory.Exists(imageDirectory)) { Directory.CreateDirectory(imageDirectory); } if (!string.IsNullOrWhiteSpace(settings.CoverImage)) { using var client = new HttpClient(); var imageResult = await client.GetAsync(new Uri(options.GhostUrl, settings.CoverImage)); if (imageResult.IsSuccessStatusCode) { using var imageStream = await imageResult.Content.ReadAsStreamAsync(); using var memoryStream = new MemoryStream(); await imageStream.CopyToAsync(memoryStream); var widths = new[] { 600, 1000, 2000 }; foreach (var width in widths) { memoryStream.Position = 0; using var image = await Image.LoadAsync(memoryStream); index.ImageHeight = image.Height; index.ImageWidth = image.Width; image.Mutate(context => context.Resize(width, 0)); await image.SaveAsPngAsync(Path.Combine(imageDirectory, width + ".png")); } } } viewDataDictionary.Model = index; var batch = 1; while (posts.Length > 0) { var directory = options.OutputDirectory; if (batch > 1) { directory = Path.Combine(directory, "index", batch.ToString()); } if (batch == 1) { index.Previous = null; } else if (batch == 2) { index.Previous = "/"; } else { index.Previous = "/index/" + (batch - 1) + "/"; } if (posts.Length > postsToDisplay) { index.Next = "/index/" + (batch + 1) + "/"; } else { index.Next = null; } using (var stringWriter = new StringWriter()) { var view = engine.GetView(".", $"/Templates/index.cshtml", true); var viewContext = new ViewContext(actionContext, view.View, viewDataDictionary, tempDataDictionary, stringWriter, htmlHelperOptions); index.PostsToDisplay = posts.Take(postsToDisplay).ToArray(); await view.View.RenderAsync(viewContext); var result = stringWriter.ToString(); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(Path.Combine(directory, "index.html"), result); } posts = posts.Skip(postsToDisplay).ToArray(); batch++; } }
private static async Task HandleTagAsync(Tag tag, Post[] posts, Settings settings, TemplatingOptions options, IServiceProvider services, IRazorViewEngine engine) { var postsToDisplay = 27; 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(); posts = posts.Where(x => x.Tags.Any(x => x.Id == tag.Id)).OrderByDescending(x => x.PublishedAt).ToArray(); tag.PostCount = posts.Length; var actionContext = new ActionContext(httpContext, routeData, actionDescriptor, modelStateDictionary); var viewDataDictionary = new ViewDataDictionary(modelMetadataProvider, modelStateDictionary); var tempDataDictionary = new TempDataDictionary(httpContext, tempDataProvider); viewDataDictionary.Model = tag; var batch = 1; while (posts.Length > 0) { var directory = Path.Combine(options.OutputDirectory, "tag", tag.Slug); if (batch > 1) { directory = Path.Combine(directory, batch.ToString()); } if (batch == 1) { tag.Previous = null; } else if (batch == 2) { tag.Previous = tag.Url; } else { tag.Previous = tag.Url + (batch - 1) + "/"; } if (posts.Length > postsToDisplay) { tag.Next = tag.Url + (batch + 1) + "/"; } else { tag.Next = null; } using (var stringWriter = new StringWriter()) { var view = engine.GetView(".", $"/Templates/tag.cshtml", true); var viewContext = new ViewContext(actionContext, view.View, viewDataDictionary, tempDataDictionary, stringWriter, htmlHelperOptions); tag.PostsToDisplay = posts.Take(postsToDisplay).ToArray(); await view.View.RenderAsync(viewContext); var result = stringWriter.ToString(); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(Path.Combine(directory, "index.html"), result); } posts = posts.Skip(postsToDisplay).ToArray(); batch++; } }
public static async Task <IHtmlContent> RenderActionAsync(this HttpContext context, string action, string controller, string area, object?[]?parameters = null, ViewContext?existingViewContext = null) { if (action is null) { throw new ArgumentNullException(nameof(action)); } if (controller is null) { throw new ArgumentNullException(nameof(controller)); } HttpContext currentHttpContext = existingViewContext?.HttpContext ?? context; parameters ??= Array.Empty <object>(); // fetching required services for invocation IHttpContextFactory httpContextFactory = GetServiceOrFail <IHttpContextFactory>(currentHttpContext); HttpContext newHttpContext = httpContextFactory.Create(currentHttpContext.Features); IActionInvokerFactory actionInvokerFactory = GetServiceOrFail <IActionInvokerFactory>(newHttpContext); IActionDescriptorCollectionProvider actionSelector = GetServiceOrFail <IActionDescriptorCollectionProvider>(newHttpContext); // creating new action invocation context RouteData routeData = new RouteData(); RouteValueDictionary routeValues = new RouteValueDictionary(new { area, controller, action }); IRazorViewEngine ViewEngine = GetServiceOrFail <IRazorViewEngine>(newHttpContext); newHttpContext.Response.Body = new MemoryStream(); routeData.PushState(null, routeValues, null); Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor = actionSelector.ActionDescriptors.Items.First(i => i.RouteValues["Controller"] == controller && i.RouteValues["Action"] == action); ActionContext actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor); //We're not invoking this using an invoker beacause it doesn't support as many object types as parameters. IControllerFactory cf = GetServiceOrFail <IControllerFactory>(newHttpContext); //build the controller Controller c = (Controller)cf.CreateController(new ControllerContext(actionContext)); //call the action to build the information required to fill the view ViewResult?viewResult = c.GetType()?.GetMethod(action)?.Invoke(c, parameters) as ViewResult; //Find the view the action says it uses ViewEngineResult result = ViewEngine.FindView(actionContext, viewResult?.ViewName ?? action, false); string htmlContent = string.Empty; using (StringWriter output = new StringWriter()) { HtmlHelperOptions options; if (existingViewContext != null) { options = new HtmlHelperOptions() { ClientValidationEnabled = existingViewContext.ClientValidationEnabled, Html5DateRenderingMode = existingViewContext.Html5DateRenderingMode, ValidationSummaryMessageElement = existingViewContext.ValidationSummaryMessageElement, ValidationMessageElement = existingViewContext.ValidationMessageElement }; } else { options = new HtmlHelperOptions() { ClientValidationEnabled = true, Html5DateRenderingMode = Html5DateRenderingMode.CurrentCulture, ValidationSummaryMessageElement = "validation-summary-errors", ValidationMessageElement = "validation-summary-messages" }; } ViewContext viewcontext = new ViewContext(actionContext, result.View, viewResult?.ViewData, viewResult?.TempData, output, options); await result.View.RenderAsync(viewcontext).ConfigureAwait(false); htmlContent = output.ToString(); } return(new HtmlString(htmlContent)); }
public async Task <string> RenderStringAsync <TModel>(string name, TModel model, IReadOnlyDictionary <string, object> tempData = null, HtmlHelperOptions htmlHelperOptions = null) { var actionContext = new ActionContext(new DefaultHttpContext { RequestServices = _serviceProvider }, new RouteData(), new ActionDescriptor()); var viewEngineResult = _viewEngine.FindView(actionContext, name, false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn't find view '{name}'"); } var tempDataDictionary = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider); if (tempData != null) { foreach (var(key, value) in tempData) { tempDataDictionary.Add(key, value); } } var view = viewEngineResult.View; await using var output = new StringWriter(); var viewContext = new ViewContext( actionContext, view, new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, tempDataDictionary , output, htmlHelperOptions ?? new HtmlHelperOptions()); await view.RenderAsync(viewContext); return(output.ToString()); }
public FormLabelTagHelper(IOptions<HtmlHelperOptions> options) { Options = options.Value; }