public static async Task <IHtmlContent> Component(this IViewComponentHelper viewComponentHelper, string moduleName, string viewComponentName) { if (InvocationHub.IsModuleInDebugMode()) { return(await viewComponentHelper.InvokeAsync(viewComponentName)); } else { return(await viewComponentHelper.InvokeAsync("Renderer", new { moduleName, viewComponentName })); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); //var model = (FloatingAction)context.AllAttributes["model"]?.Value; var content = _viewComponentHelper.InvokeAsync(typeof(FloatingActionButton), new { model = Model }); content.RunSynchronously(); output.Content.SetHtmlContent(content.Result); }
async Task <IHtmlContent> InvokeViewComponentAsync(string viewName, object arguments) { if (!(_viewComponentHelper is DefaultViewComponentHelper helper)) { throw new ArgumentNullException( $"{_viewComponentHelper.GetType()} cannot be converted to DefaultViewComponentHelper"); } // Contextualize view component helper.Contextualize(ViewContext); // Log the invocation, we can't use try / catch around our view component helper :( if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation($"Attempting to invoke view component \"{viewName}\"."); } try { return(await _viewComponentHelper.InvokeAsync(viewName, arguments)); } catch (Exception e) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(e, $"An exception occurred whilst invoking the view component with name \"{viewName}\". {e.Message}"); } throw; } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); var content = await _viewComponentHelper.InvokeAsync(typeof(WidgetViewComponent), new { name = Name }); output.Content.SetHtmlContent(content); }
/// <summary> /// Outputs widget area html or nothing if the given widget area id is not found. /// </summary> /// <param name="context"></param> /// <param name="output"></param> /// <returns></returns> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagMode = TagMode.StartTagAndEndTag; output.TagName = "div"; output.Attributes.SetAttribute("class", "widgets"); ((IViewContextAware)this.viewComponentHelper).Contextualize(ViewContext); var area = await widgetService.GetAreaAsync(Id); if (area == null) { return; } for (int i = 0; i < area.WidgetIds.Length; i++) { var widgetIns = area.WidgetInstances[i]; var widget = area.Widgets[i]; var content = await viewComponentHelper.InvokeAsync(widgetIns.Folder, widget); output.Content.AppendHtml(content.GetString()); } }
/// <summary> /// Starts loading a component without blocking the thread /// </summary> public void StartLoading(PreRenderComponentInfo <TId> componentInfo) { var invokeAsync = _componentHelper.InvokeAsync(componentInfo.ComponentType, new { input = componentInfo.Input, screenModel = _screenModel }); _componentInvocations.Add(componentInfo.ComponentId, invokeAsync); }
public async Task <IHtmlContent> RenderAsync(IViewComponentHelper component, string mywidget) { var componentType = _widgetOptions.Widgets.Single(w => w.Name.Equals(mywidget)).ViewComponentType; var args = new object(); return(await component.InvokeAsync(componentType, args)); }
public async Task <IHtmlContent> ContentAsync(IViewComponentHelper helper) { var actionContext = _actionContextAccessor.ActionContext; var viewComponentName = actionContext.RouteData.DataTokens["ViewComponent"] as string; var compositeValueProvider = await CompositeValueProvider.CreateAsync(actionContext, _optionsAccessor.Value.ValueProviderFactories); var pluginViewComponent = _viewComponentSelector.SelectComponent(viewComponentName); var parameterBinder = ActivatorUtilities.CreateInstance <ParameterBinder>(_serviceProvider); var parameterBag = new Dictionary <string, object>(); foreach (var parameter in pluginViewComponent.Parameters) { var parameterDescriptor = new ParameterDescriptor { BindingInfo = BindingInfo.GetBindingInfo(parameter.GetCustomAttributes()), Name = parameter.Name, ParameterType = parameter.ParameterType, }; var result = await parameterBinder.BindModelAsync( actionContext, compositeValueProvider, parameterDescriptor); parameterBag[parameter.Name] = result.IsModelSet ? result.Model : null; } return(await helper.InvokeAsync(viewComponentName, parameterBag)); }
public async static Task <IHtmlContent> MotleyFlash( this IViewComponentHelper value, string view = null) { if (string.IsNullOrWhiteSpace(view)) { return(await value.InvokeAsync <MotleyFlashViewComponent>(new MotleyFlashViewComponentOptions())); } else { return(await value.InvokeAsync <MotleyFlashViewComponent>(new MotleyFlashViewComponentOptions() { View = view })); } }
public static Task <IHtmlContent> Breadcrumb(this IViewComponentHelper componentHelper, string title, Dictionary <string, string> hrefAndName = null) { if (hrefAndName == null) { hrefAndName = new Dictionary <string, string>(); } return(componentHelper.InvokeAsync("Breadcrumb", new BreadcumbModel(title, hrefAndName))); }
private async Task SetHtmlContent(TagHelperOutput output, string name, Dictionary <string, string> options) { ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); var content = await _viewComponentHelper.InvokeAsync(name, options); output.TagName = null; // prevents taghelper tags being rendered in the final HTML output.Content.SetHtmlContent(content); }
public HtmlString RenderForKeyAsHtmlString(IViewComponentHelper component, string host, string key, string title = "", bool loadondemand = false) { StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); component.InvokeAsync("HelpInstruction", new { apirooturl = _apirooturl, hostkey = host, datakey = key, label = title, ondemand = loadondemand }).Result.WriteTo(writer, HtmlEncoder.Default); return(new HtmlString(writer.ToString())); }
/// <summary> /// Invokes a view component of type <typeparamref name="TComponent"/>. /// </summary> /// <param name="helper">The <see cref="IViewComponentHelper"/>.</param> /// <typeparam name="TComponent">The <see cref="Type"/> of the view component.</typeparam> /// <returns>A <see cref="Task"/> that on completion returns the rendered <see cref="IHtmlContent" />. /// </returns> public static Task <IHtmlContent> InvokeAsync <TComponent>(this IViewComponentHelper helper) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return(helper.InvokeAsync(typeof(TComponent), arguments: null)); }
public static Task <HtmlString> InvokeAsync <TComponent>(this IViewComponentHelper helper, params object[] args) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return(helper.InvokeAsync(typeof(TComponent), args)); }
public async Task <IHtmlContent> InvokeAsync(IViewComponentHelper helper, string name, object arguments = null) { if (Disabled() != null && Disabled().Contains(name)) { return(await Task.FromResult(new HtmlString(""))); } return(Exists(name) ? await helper.InvokeAsync(name, arguments) : await Task.FromResult(GetContent(name))); }
private Task <IHtmlContent> GetViewComponentResult(IViewComponentHelper viewComponentHelper, ILogger logger, ViewComponentResult result) { if (result.ViewComponentType == null && result.ViewComponentName == null) { throw new InvalidOperationException(Resources.FormatViewComponentResult_NameOrTypeMustBeSet( nameof(ViewComponentResult.ViewComponentName), nameof(ViewComponentResult.ViewComponentType))); } else if (result.ViewComponentType == null) { logger.ViewComponentResultExecuting(result.ViewComponentName); return(viewComponentHelper.InvokeAsync(result.ViewComponentName, result.Arguments)); } else { logger.ViewComponentResultExecuting(result.ViewComponentType); return(viewComponentHelper.InvokeAsync(result.ViewComponentType, result.Arguments)); } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var componentName = Util.KebabToPascal(context.TagName); var matchingViewComponent = _viewComponents.FirstOrDefault(a => a.Name == componentName || a.FullName == componentName || a.FullName.EndsWith(componentName) ); if (matchingViewComponent == null) { output.Content.SetHtmlContent( $"<span style=\"color:red;border:1px dashed red;\">view component '{componentName}' not found" ); return; } SlotTagHelper.Contexts.Push(new SlotContext()); var childContent = (await output.GetChildContentAsync()).GetContent(); if (!string.IsNullOrWhiteSpace(childContent)) { SlotTagHelper.Contexts.Peek().Placements.Add(new SlotPlacement { Selector = string.Empty, TagName = null, Attributes = new TagHelperAttributeList(), Content = childContent, }); } (_viewComponentHelper as IViewContextAware).Contextualize(ViewContext); var componentParams = matchingViewComponent .GetMethod("InvokeAsync") .GetParameters(); var componentArgs = Util.ExtractComponentArgs( componentParams, Attributes ); var componentOutput = await _viewComponentHelper.InvokeAsync( matchingViewComponent, componentArgs ); output.Content.SetHtmlContent(componentOutput); SlotTagHelper.Contexts.Pop(); }
public static Task <IHtmlContent> InvokeLayoutHookAsync( this IViewComponentHelper componentHelper, string name, string layout) { return(componentHelper.InvokeAsync( typeof(LayoutHookViewComponent), new { name = name, layout = layout } )); }
public Task <IHtmlContent> InvokeAsync(string name, object arguments) { try { return(_componentHelper.InvokeAsync(name, arguments)); } catch (Exception) { throw; } }
public async Task <IHtmlContent> InvokeAsync(IViewComponentHelper helper, string name, object arguments = null) { if (Disabled() != null && Disabled().Contains(name)) { return(await Task.FromResult(new HtmlString(""))); } try { return(Exists(name) ? await helper.InvokeAsync(name, arguments) : await Task.FromResult(new HtmlString(""))); } catch (System.Exception ex) { this.logger.LogError($"Error loading widget: {ex.Message}"); return(await Task.FromResult(new HtmlString(""))); } }
/// <inheritdoc /> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { // this tag heper doesn't actually output anything. // It does render our ViewComponent afterwards, if there is any content for it. output.SuppressOutput(); IList <FeedbackMessageModel> model = null; // TempData takes precedence over static attributes, if we're set to use it if (UseTempData) { try { model = ViewContext.TempData.GetFeedbackMessages(); } catch (JsonSerializationException) { // We don't care; model will be null and so we'll pick up outside this block } } // Either we're not using TempData, or none was successfully set if (model is null && !string.IsNullOrWhiteSpace(Message)) { model = new List <FeedbackMessageModel> { new FeedbackMessageModel() { Message = Message, Type = Type, Dismissable = Dismissable } } } ; if (model is null) { return; } ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); var content = await _viewComponentHelper.InvokeAsync( typeof(UonFeedbackMessage), model); output.Content.SetHtmlContent(content); } }
private async Task RenderControllerAction(string controller, string action, Rendering rendering, IHtmlContentBuilder output, ViewContext viewContext, PageData pageData) { var context = await GetViewContext(rendering, viewContext, pageData, new NullView(), viewContext.Writer); var toContext = _viewComponentHelper as IViewContextAware; if (toContext != null) { toContext.Contextualize(context); } try { var result = await _viewComponentHelper.InvokeAsync(action + ": " + controller); output.AppendHtml(result); } catch (InvalidOperationException exc) { output.AppendHtml($"<div class=\"alert alert-danger\"><strong>{exc.Message}</strong> not found!</div>"); } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { try { ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); var content = await _viewComponentHelper.InvokeAsync(typeof(BaseViewComponent), new { component = Component }); output.TagMode = TagMode.StartTagAndEndTag; output.Content.SetHtmlContent(content); } catch (Exception e) { output.Content.SetHtmlContent( "<p class=\"error\">EXCEPTION rendering JSViewComponent: " + Component?.ComponentFullName + "</p>" + Environment.NewLine + "<!-- " + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine + "-->" ); } }
public static async Task <IHtmlContent> BlockContainerAsync(this IViewComponentHelper component, Dictionary <string, List <BlockModel> > containers, string containerId) { var builder = new HtmlContentBuilder(); if (containers == null || !containers.TryGetValue(containerId, out var blocks) || blocks.Count == 0) { return(builder); } foreach (var blockModel in blocks) { var fieldTemplate = _fieldTemplateService.Value.Get <BlockFieldTemplate>(blockModel.FieldTemplateSystemId); if (string.IsNullOrWhiteSpace(fieldTemplate?.TemplatePath) || fieldTemplate.TemplatePath.IndexOf("MVC:", StringComparison.OrdinalIgnoreCase) == -1) { throw new InvalidOperationException("Could not find template for block."); } var templateDefaults = fieldTemplate.TemplatePath.Split(':').Skip(1).ToArray(); if (templateDefaults.Length < 1) { throw new InvalidOperationException("Could not find template for block."); } var controllerType = Type.GetType(templateDefaults[0], true, true); if (controllerType == null) { throw new InvalidOperationException("Could not find template for block."); } var tagBuilder = new TagBuilder("section"); tagBuilder.Attributes["data-litium-block-id"] = blockModel.SystemId.ToString(); tagBuilder.InnerHtml.AppendHtml(await component.InvokeAsync(controllerType, blockModel)); builder.AppendHtml(tagBuilder); builder.AppendLine(); } return(builder); }
public async Task <IHtmlContent> InvokeAsync(Abstractions.IView view) { // We always need a view name to invoke if (string.IsNullOrEmpty(view.ViewName)) { throw new ArgumentNullException(nameof(view.ViewName)); } if (!(_viewComponentHelper is DefaultViewComponentHelper helper)) { throw new ArgumentNullException( $"{_viewComponentHelper.GetType()} cannot be converted to DefaultViewComponentHelper"); } // Contextualize view component helper.Contextualize(ViewContext); // Log the invocation if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation($"Attempting to invoke view component \"{view.ViewName}\"."); } try { return(await _viewComponentHelper.InvokeAsync(view.ViewName, view.Model)); } catch (Exception e) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(e, $"An exception occurred whilst invoking the view component with name \"{view.ViewName}\". {e.Message}"); } throw; } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (For != null) { if (For.Metadata.ElementMetadata != null) { AllowedProperties = For.Metadata.ElementMetadata.Properties.Where(p => p.ShowForDisplay).ToList(); } else { AllowedProperties = For.Metadata.Properties.Where(p => p.ShowForDisplay).ToList(); } ColumnNames = AllowedProperties.Select(p => p.DisplayOrName()).ToList(); } output.Attributes.RemoveAll("data-table"); output.Attributes.TryGetAttribute("id", out TagHelperAttribute idAttribute); if (idAttribute == null) { TableID = "dt-" + context.UniqueId; output.Attributes.SetAttribute("id", TableID); } else { TableID = idAttribute.Value.ToString(); } if (For != null) { output.TagName = null; // remove the original tag, the View Component will generate the table } output.Content.AppendHtml(await output.GetChildContentAsync()); ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); var content = await _viewComponentHelper.InvokeAsync(typeof(DataTableViewComponent), this); output.Content.AppendHtml(content); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } if (NumberOfColumns < 1 || NumberOfColumns > 12) { throw new ArgumentOutOfRangeException("NumberOfColumns", "The number of columns must be at least 1 and at most 12."); } if (For == null) { output.SuppressOutput(); return; } var collection = For.Model as ICollection; if (collection == null) { throw new ArgumentOutOfRangeException("For", "The Model Expression need to be a collection."); } //add the view context of the current view to the view component, enable to invoke ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext); output.TagName = "div"; output.Attributes.SetAttribute("class", "container-fluid"); var columnsInRow = 1; var rowsDone = 0; var numberOfItemsDone = 0; var numberOfExtraColumnsInLastRow = 0; //calculate the needed table structure int numberOfRows = collection.Count / NumberOfColumns; foreach (var item in collection) { if (columnsInRow == 1) { output.Content.AppendHtml(@"<div class=""row"">"); } output.Content.AppendHtml(GetColumnDivTag()); var viewContent = await _viewComponentHelper.InvokeAsync(ViewComponentName, item); output.Content.AppendHtml(viewContent); output.Content.AppendHtml("</div>"); bool isLastItem = (collection.Count == numberOfItemsDone + 1); if ((columnsInRow == NumberOfColumns) || isLastItem) { if (isLastItem) { numberOfExtraColumnsInLastRow = NumberOfColumns - columnsInRow; output.Content.AppendHtml((RenderExtraColumns(numberOfExtraColumnsInLastRow))); } output.Content.AppendHtml("</div>"); columnsInRow = 1; rowsDone++; } else { columnsInRow++; } numberOfItemsDone++; } }
public async Task <IHtmlContent> RenderAsync(IViewComponentHelper componentHelper, string widgetName, object args = null) { var componentType = _widgetOptions.Widgets.Single(w => w.Name.Equals(widgetName)).ViewComponentType; return(await componentHelper.InvokeAsync(componentType, args ?? new object())); }
public Task <string> InvokeViewComponentAsync(string componentName, ViewDataDictionary viewData, object arguments) { Guard.NotEmpty(componentName, nameof(componentName)); return(InvokeViewComponentInternal(viewData, () => _viewComponentHelper.InvokeAsync(componentName, arguments))); }
public static async Task <HtmlString> InvokeAsync <TComponent>([NotNull] this IViewComponentHelper helper, params object[] args) { return(await helper.InvokeAsync(typeof(TComponent), args)); }
private Task<IHtmlContent> GetViewComponentResult(IViewComponentHelper viewComponentHelper, ILogger logger, ViewComponentResult result) { if (result.ViewComponentType == null && result.ViewComponentName == null) { throw new InvalidOperationException(Resources.FormatViewComponentResult_NameOrTypeMustBeSet( nameof(ViewComponentResult.ViewComponentName), nameof(ViewComponentResult.ViewComponentType))); } else if (result.ViewComponentType == null) { logger.ViewComponentResultExecuting(result.ViewComponentName); return viewComponentHelper.InvokeAsync(result.ViewComponentName, result.Arguments); } else { logger.ViewComponentResultExecuting(result.ViewComponentType); return viewComponentHelper.InvokeAsync(result.ViewComponentType, result.Arguments); } }