private void MakeActive(TagHelperOutput output) { var classAttr = output.Attributes.FirstOrDefault(a => a.Name == "class"); if (classAttr == null) { classAttr = new TagHelperAttribute("class", "active"); output.Attributes.Add(classAttr); } else if (classAttr.Value == null || classAttr.Value.ToString().IndexOf("active") < 0) { output.Attributes.SetAttribute("class", classAttr.Value == null ? "active" : classAttr.Value.ToString() + " active"); } }
private void MakeActive(TagHelperOutput output) { var classAttribute = output.Attributes.FirstOrDefault(a => a.Name == "class"); if (classAttribute == null) { classAttribute = new TagHelperAttribute("class", "active"); output.Attributes.Add(classAttribute); } else if (classAttribute.Value?.ToString().Contains("active", StringComparison.Ordinal) != true) { output.Attributes.SetAttribute("class", classAttribute.Value is null ? "active" : classAttribute.Value + " active"); } }
private void MakeActive(TagHelperOutput output) { // Get the tag attribute var classAttr = output.Attributes.FirstOrDefault(a => a.Name == "class"); if (classAttr == null) { // Add new class tag with active attribute classAttr = new TagHelperAttribute("class", "active"); output.Attributes.Add(classAttr); } else if (classAttr.Value == null || classAttr.Value.ToString().IndexOf("active") < 0) { // Adds active attribute output.Attributes.SetAttribute("class", classAttr.Value == null ? "active" : classAttr.Value + " active"); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var existingClasses = output.Attributes .FirstOrDefault(_ => _.Name == "class"); string availability = ""; if (CurrentDate) { availability = nameof(PsScheduleDateStatus.Current); } else if (Schedule == null && (!Booking || BookedDate == default(DateTime))) { availability = nameof(PsScheduleDateStatus.Available); } else if (Schedule?.StartTime.HasValue == true || (Booking && BookedDate != default(DateTime))) { availability = nameof(PsScheduleDateStatus.Time); if (Schedule?.StartTime.HasValue == true) { var timeString = JsonConvert.SerializeObject(new List <string> { Schedule.StartTime.Value.ToString("hh:mm tt"), Schedule.EndTime.Value.ToString("hh:mm tt") }); output.Attributes.Add("data-time", timeString); } } else if (Schedule?.StartTime.HasValue == false) { availability = nameof(PsScheduleDateStatus.Unavailable); } if (!Booking) { output.Attributes.Add("data-availability", availability); } if (!existingClasses.Value.ToString().Contains("unselectable") || (Booking && availability == nameof(PsScheduleDateStatus.Unavailable))) { output.Attributes.Remove(existingClasses); var attribute = new TagHelperAttribute("class", $"{existingClasses.Value} {availability.ToLower()}"); output.Attributes.Add(attribute); } }
public void TryGetAttribute_ReturnsExpectedValueAndAttribute( IEnumerable <TagHelperAttribute> initialAttributes, string nameToLookup, TagHelperAttribute expectedAttribute, bool expectedResult) { // Arrange var attributes = new TagHelperAttributeList(initialAttributes); TagHelperAttribute attribute; // Act var result = attributes.TryGetAttribute(nameToLookup, out attribute); // Assert Assert.Equal(expectedResult, result); Assert.Equal(expectedAttribute, attribute, CaseSensitiveTagHelperAttributeComparer.Default); }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { using (var localizationManagerWrapper = IocManager.Instance.ResolveAsDisposable <ILocalizationManager>()) { var localizationManager = localizationManagerWrapper.Object; var localizationSource = localizationManager.GetSource(MasterConsts.LocalizationSourceName); var dic = GetDictionary(DictionaryName); return(Task.Run(() => { if (context.TagName == "select") { foreach (KeyValuePair <string, string> item in dic) { output.Content.AppendHtml($"<option value='{item.Key}' {(Value == item.Key ? "selected" : "")}>{localizationSource.GetString(item.Value)}</option>"); } } else if (context.TagName == "radio") { output.TagName = "div"; TagHelperAttribute nameAttribute = null; context.AllAttributes.TryGetAttribute("name", out nameAttribute); foreach (KeyValuePair <string, string> item in dic) { output.PostContent.AppendHtml($"<input type='radio' name='{nameAttribute?.Value}' value='{ item.Key}' {(Value == item.Key ? "checked" : "")} title='{localizationSource.GetString(item.Value)}' >"); } } else if (context.TagName == "checkbox") { output.TagName = "div"; TagHelperAttribute nameAttribute = null; TagHelperAttribute skinAttribute = null; context.AllAttributes.TryGetAttribute("name", out nameAttribute); context.AllAttributes.TryGetAttribute("skin", out skinAttribute); var value_arr = Value.Split(',').ToList(); foreach (KeyValuePair <string, string> item in dic) { output.Content.AppendHtml($"<input type='checkbox' name='{nameAttribute?.Value}' value='{ item.Key}'{(value_arr.Contains(item.Key) ? "checked" : "")} title='{localizationSource.GetString(item.Value)}' lay-skin='{skinAttribute?.Value}'>"); } } })); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { string emailHash; using (var md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(EmailAddress)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("x2")); } emailHash = sb.ToString(); } var scheme = contextAccessor.HttpContext.Request.Scheme; string format; if (scheme == "https") { format = httpsEndpointFormat; } else { format = httpEndpointFormat; } var url = string.Format( CultureInfo.InvariantCulture, format, emailHash, Size, DefaultImage, Rating ); var att = new TagHelperAttribute("gravatar-email"); output.Attributes.Remove(att); output.Attributes.Add("src", url); }
private void MakeActive(TagHelperOutput output) { ActiveRouteClass = string.IsNullOrWhiteSpace(ActiveRouteClass) ? "active" : ActiveRouteClass; var classAttr = output.Attributes.FirstOrDefault(a => a.Name == "class"); if (classAttr == null) { classAttr = new TagHelperAttribute("class", ActiveRouteClass); output.Attributes.Add(classAttr); } else if (classAttr.Value == null || classAttr.Value.ToString().IndexOf(ActiveRouteClass) < 0) { output.Attributes.SetAttribute("class", classAttr.Value == null ? ActiveRouteClass : classAttr.Value.ToString() + " " + ActiveRouteClass); } }
/// <summary>Сделать элемент активным</summary> /// <param name="output">Вывод элемента</param> private void MakeActive(TagHelperOutput output) { var class_attribute = output.Attributes.FirstOrDefault(a => a.Name == "class"); if (class_attribute is null) { class_attribute = new TagHelperAttribute("class", "active"); output.Attributes.Add(class_attribute); } else { output.Attributes.SetAttribute( "class", class_attribute.Value is null ? ActiveClass : string.Join(" ", class_attribute.Value, ActiveClass)); } }
public void AddsActiveClassForMatchingUrlWithThreeSegmentsFuzzyMatch() { //Arrange contextAccessor.HttpContext.Request.Path = "/primary/secondary/tertiary"; helper.FuzzySegmentMatch = true; helper.Area = ""; helper.Controller = "Home"; helper.Action = "Primary"; //Act helper.Process(tagHelperContext, tagHelperOutput); //Assert TagHelperAttribute classAttribute = null; tagHelperOutput.Attributes.TryGetAttribute("class", out classAttribute); Assert.AreEqual("active", classAttribute.Value); }
public void CopyTo_CopiesAttributes( IEnumerable <TagHelperAttribute> initialAttributes, TagHelperAttribute[] attributesToCopy, int locationToCopy, IEnumerable <TagHelperAttribute> expectedAttributes) { // Arrange var attributes = new TagHelperAttributeList(initialAttributes); var attributeDestination = new TagHelperAttribute[expectedAttributes.Count()]; attributes.ToArray().CopyTo(attributeDestination, 0); // Act attributesToCopy.CopyTo(attributeDestination, locationToCopy); // Assert Assert.Equal(expectedAttributes, attributeDestination, CaseSensitiveTagHelperAttributeComparer.Default); }
public override void Process(TagHelperContext context, TagHelperOutput output) { base.Process(context, output); if (context.AllAttributes["required"] == null) { var isRequired = IsRequired(For.ModelExplorer.Metadata.ValidatorMetadata); if (isRequired) { //output.Attributes.Add("required", "required"); var attr = new TagHelperAttribute("required", string.Empty, HtmlAttributeValueStyle.Minimized); output.Attributes.Add(attr); } foreach (var attribute in output.Attributes) { if (attribute.Name == "data-val") { output.Attributes.Remove(attribute); break; } } // tagBuilder.MergeAttribute("required", string.Empty); foreach (var attribute in output.Attributes) { if (attribute.Name == "data-val-required") { // var builder = new TagBuilder("input"); // builder.MergeAttribute("required", string.Empty); output.Attributes.Remove(attribute); break; } } } }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (IsAjax) { if (output.Attributes.ContainsName(ClassAttributeName)) { var attr = output.Attributes.FirstOrDefault(i => i.Name == ClassAttributeName); var classTag = new TagHelperAttribute(ClassAttributeName, $"{attr.Value} {ClassAttributeAjaxValue}"); output.Attributes.Remove(attr); output.Attributes.Add(classTag); } else { var classTag = new TagHelperAttribute(ClassAttributeName, ClassAttributeAjaxValue); output.Attributes.Add(classTag); } } }
/// <summary> /// A method to either create the class attribute and assign a class to an HTML element, or to append a new class to the existing attribute if needed. /// </summary> /// <param name="output">The TagHelperOutput class to add the class to.</param> /// <returns>The input TagHelperOutput class will be returned with the added class.</returns> public static TagHelperOutput AddClass(this TagHelperOutput output, string newClass) { var existingClass = output.Attributes.FirstOrDefault(f => f.Name == "class"); var cssClass = string.Empty; if (existingClass != null) { cssClass = existingClass.Value.ToString(); } cssClass = $"{cssClass} {newClass}"; var ta = new TagHelperAttribute("class", cssClass); output.Attributes.Remove(existingClass); output.Attributes.Add(ta); return(output); }
public CssClassAttributeManager(TagHelperAttributeList attributes, HtmlEncoder htmlEncoder) { _attributes = attributes; _htmlEncoder = htmlEncoder; _classAttribute = _attributes["class"]; var classAttributeHtml = _classAttribute?.Value as IHtmlContent; if (classAttributeHtml != null) { var writer = new StringWriter(); classAttributeHtml.WriteTo(writer, _htmlEncoder); _existingClasses = new[] { writer.ToString() }; } else { _existingClasses = _classAttribute?.Value?.ToString().Split(' '); } }
static public void CreateOrMergeAttribute(this TagHelperOutput output, string name, object content) { var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name); if (currentAttribute == null) { var attribute = new TagHelperAttribute(name, content); output.Attributes.Add(attribute); } else { var newAttribute = new TagHelperAttribute( name, $"{currentAttribute.Value.ToString()} {content.ToString()}", currentAttribute.ValueStyle); output.Attributes.Remove(currentAttribute); output.Attributes.Add(newAttribute); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var loggedInUser = LoggedInUser <GoblinIdentityUserModel> .Current?.Data; if (Permissions?.Any() == true && loggedInUser?.Permissions.Any(x => Permissions.Contains(x)) != true) { switch (Mode) { case SecurityMode.Hide: { output.SuppressOutput(); return; } case SecurityMode.Disable: { var attribute = new TagHelperAttribute("disabled", "disabled"); output.Attributes.Add(attribute); break; } case SecurityMode.Readonly: { var attribute = new TagHelperAttribute("readonly", "readonly"); output.Attributes.Add(attribute); break; } default: { throw new ArgumentOutOfRangeException(); } } } base.Process(context, output); }
private static void CopyHtmlAttribute( int allAttributeIndex, TagHelperOutput tagHelperOutput, TagHelperContext context) { var existingAttribute = context.AllAttributes[allAttributeIndex]; var copiedAttribute = new TagHelperAttribute { Name = existingAttribute.Name, Value = existingAttribute.Value, Minimized = existingAttribute.Minimized }; // Move backwards through context.AllAttributes from the provided index until we find a familiar attribute // in tagHelperOutput where we can insert the copied value after the familiar one. for (var i = allAttributeIndex - 1; i >= 0; i--) { var previousName = context.AllAttributes[i].Name; var index = IndexOfFirstMatch(previousName, tagHelperOutput.Attributes); if (index != -1) { tagHelperOutput.Attributes.Insert(index + 1, copiedAttribute); return; } } // Move forward through context.AllAttributes from the provided index until we find a familiar attribute in // tagHelperOutput where we can insert the copied value. for (var i = allAttributeIndex + 1; i < context.AllAttributes.Count; i++) { var nextName = context.AllAttributes[i].Name; var index = IndexOfFirstMatch(nextName, tagHelperOutput.Attributes); if (index != -1) { tagHelperOutput.Attributes.Insert(index, copiedAttribute); return; } } // Couldn't determine the attribute's location, add it to the end. tagHelperOutput.Attributes.Add(copiedAttribute); }
public void MergeAttributes_Maintains_TagHelperOutputAttributeValues() { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "p", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>( new DefaultTagHelperContent())); var expectedAttribute = new TagHelperAttribute("class", "btn"); tagHelperOutput.Attributes.Add(expectedAttribute); var tagBuilder = new TagBuilder("p"); // Act tagHelperOutput.MergeAttributes(tagBuilder); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal(expectedAttribute, attribute); }
public void MergeAttributes_Maintains_TagHelperOutputAttributeValues() { // Arrange var tagHelperOutput = new TagHelperOutput( "p", attributes: new TagHelperAttributeList()); var expectedAttribute = new TagHelperAttribute("class", "btn"); tagHelperOutput.Attributes.Add(expectedAttribute); var tagBuilder = new TagBuilder("p"); // Act tagHelperOutput.MergeAttributes(tagBuilder); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal(expectedAttribute, attribute); }
public void AddsActiveClassForMatchingUrlWithRouteData() { //Arrange contextAccessor.HttpContext.Request.Path = "/primary/secondary/tertiary/foobar"; helper.FuzzySegmentMatch = false; helper.Area = ""; helper.Controller = "Home"; helper.Action = "Quadrary"; helper.RouteValues = new Dictionary <string, string>(); helper.RouteValues.Add("aThing", "foobar"); //Act helper.Process(tagHelperContext, tagHelperOutput); //Assert TagHelperAttribute classAttribute = null; tagHelperOutput.Attributes.TryGetAttribute("class", out classAttribute); Assert.AreEqual("active", classAttribute.Value); }
public void MergeAttributes_DoesNotEncode_TagHelperOutputAttributeValues() { // Arrange var tagHelperOutput = new TagHelperOutput( "p", attributes: new TagHelperAttributeList()); var tagBuilder = new TagBuilder("p"); var expectedAttribute = new TagHelperAttribute("visible", "val < 3"); tagBuilder.Attributes.Add("visible", "val < 3"); // Act tagHelperOutput.MergeAttributes(tagBuilder); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal(expectedAttribute, attribute); }
/// <summary>Метод делает ссылку активной</summary> /// <param name="tagHelperOutput"></param> private static void MakeActive(TagHelperOutput tagHelperOutput) { TagHelperAttribute class_attribute = tagHelperOutput.Attributes.FirstOrDefault(attr => attr.Name == "class"); //ищем атрибут класса в элементе разметки if (class_attribute is null) { tagHelperOutput.Attributes.Add("class", "active"); //если такого атрибута нет, то добавляем его с нужным значением } else { if (class_attribute.Value.ToString()?.Contains("active") ?? false) { return; //если в атрибуте уже есть значение active, то ничего не делаем } tagHelperOutput.Attributes.SetAttribute("class", class_attribute.Value is null ? "active" //если значения нет, то устанавливаем его : class_attribute.Value + " active"); //иначе добавляем его к остальным значениям } }
/// <inheritdoc /> public override void Process([App.NotNull] TagHelperContext context, [App.NotNull] TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } // Pass through attribute that is also a well-known HTML attribute if (this.Href != null) { output.CopyHtmlAttribute(HtmlHrefAttribute, context); } // Retrieve the TagHelperOutput variation of the "href" attribute in case other TagHelpers in the // pipeline have touched the value. If the value is already encoded this TagHelper may // not function properly. TagHelperAttribute hrefAttribute = output.Attributes[HtmlHrefAttribute]; this.Href = hrefAttribute?.Value as string; if (hrefAttribute == null) { return; } // Output path in polyfill detection code with version string output.Attributes.Remove(hrefAttribute); output.Attributes.RemoveAll("rel"); string path = this._fileVersionProvider.AddFileVersionToPath(this.ViewContext.HttpContext.Request.PathBase, this.Href); output.TagName = "script"; output.TagMode = TagMode.StartTagAndEndTag; output.Content.SetHtmlContent( $"{this.PolyfillTest}||ss('{JavaScriptEncoder.Default.Encode(path)}')" ); }
public override void Process(TagHelperContext context, TagHelperOutput output) { // we don't need to output this attribute it was only used for matching in razor TagHelperAttribute modalAttribute = null; output.Attributes.TryGetAttribute(BootstrapModalLinkAttributeName, out modalAttribute); if (modalAttribute != null) { output.Attributes.Remove(modalAttribute); } var dialogDivId = Guid.NewGuid().ToString(); output.Attributes.Add("data-ajax", "true"); output.Attributes.Add("data-ajax-begin", "prepareModalDialog('" + dialogDivId + "')"); output.Attributes.Add("data-ajax-failure", "clearModalDialog('" + dialogDivId + "');alert('Ajax call failed')"); output.Attributes.Add("data-ajax-method", "GET"); output.Attributes.Add("data-ajax-mode", "replace"); output.Attributes.Add("data-ajax-success", "openModalDialog('" + dialogDivId + "')"); output.Attributes.Add("data-ajax-update", "#" + dialogDivId); }
public void AddsActiveClassForMatchingRouteWithNoAdditionalRouteData() { //Arrange viewContext.RouteData.Values.Add("Area", ""); viewContext.RouteData.Values.Add("Controller", "Home"); viewContext.RouteData.Values.Add("Action", "Index"); //Act helper.Process(tagHelperContext, tagHelperOutput); //Assert TagHelperAttribute classAttribute = null; tagHelperOutput.Attributes.TryGetAttribute("class", out classAttribute); Assert.AreEqual("active", classAttribute.Value); TagHelperAttribute aspActiveAttribute = null; tagHelperOutput.Attributes.TryGetAttribute("asp-is-active", out aspActiveAttribute); Assert.IsNull(aspActiveAttribute); }
public void MergeAttributes_DoesNotEncode_TagHelperOutputAttributeValues() { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "p", attributes: new TagHelperAttributeList(), getChildContentAsync: (_) => Task.FromResult <TagHelperContent>(new DefaultTagHelperContent())); var tagBuilder = new TagBuilder("p"); var expectedAttribute = new TagHelperAttribute("visible", "val < 3"); tagBuilder.Attributes.Add("visible", "val < 3"); // Act tagHelperOutput.MergeAttributes(tagBuilder); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal(expectedAttribute, attribute); }
public void DoesNotAddActiveClassNotMatchingRouteData() { //Arrange helper.RouteValues = new Dictionary <string, string>(); helper.RouteValues.Add("Id", "Foo"); helper.RouteValues.Add("Name", "Bar"); viewContext.RouteData.Values.Add("Area", ""); viewContext.RouteData.Values.Add("Controller", "Home"); viewContext.RouteData.Values.Add("Action", "Index"); viewContext.RouteData.Values.Add("Id", "Fred"); viewContext.RouteData.Values.Add("Name", "Bar"); //Act helper.Process(tagHelperContext, tagHelperOutput); //Assert TagHelperAttribute classAttribute = null; tagHelperOutput.Attributes.TryGetAttribute("class", out classAttribute); Assert.IsNull(classAttribute); }
public override void Process(TagHelperContext context, TagHelperOutput output) { // we don't need to output this attribute it was only used for matching in razor TagHelperAttribute matchAttribute = null; output.Attributes.TryGetAttribute(FormItemDefinitionAttributeName, out matchAttribute); if (matchAttribute != null) { output.Attributes.Remove(matchAttribute); } if (FormItem == null) { return; } if (FormItem.Required | !string.IsNullOrEmpty(FormItem.RegexValidationExpression) | !string.IsNullOrWhiteSpace(FormItem.MaxLengthErrorMessage) ) { output.Attributes.Add("data-val", "true"); } if (FormItem.Required) { output.Attributes.Add("data-val-required", FormItem.RequiredErrorMessage); } if (!string.IsNullOrEmpty(FormItem.RegexValidationExpression)) { output.Attributes.Add("data-val-regex", FormItem.RegexErrorMessage); output.Attributes.Add("data-val-regex-pattern", FormItem.RegexValidationExpression); } if (FormItem.MaxLength > -1 && !string.IsNullOrWhiteSpace(FormItem.MaxLengthErrorMessage)) { output.Attributes.Add("data-val-length", FormItem.RegexErrorMessage); output.Attributes.Add("data-val-length-max", FormItem.MaxLength); } //TODO: are there other unobtrusive validations that we could easily suport here? }
private void MakeActive(TagHelperOutput output) { var currentController = ViewContext.RouteData.Values["Controller"].ToString(); var currentAction = ViewContext.RouteData.Values["Action"].ToString(); var show = false; if (!String.IsNullOrWhiteSpace(Controller) && Controller.Equals(currentController, StringComparison.CurrentCultureIgnoreCase)) { show = true; } if (show && !String.IsNullOrWhiteSpace(Action) && Action.Equals(currentAction, StringComparison.CurrentCultureIgnoreCase)) { show = true; } else { show = false; } var classAttr = output.Attributes.FirstOrDefault(a => a.Name == "class"); if (classAttr == null) { classAttr = new TagHelperAttribute("class", "active"); output.Attributes.Add(classAttr); } else if (classAttr.Value == null || classAttr.Value.ToString().IndexOf("active") < 0) { if (show == true) { output.Attributes.SetAttribute("class", classAttr.Value == null ? "active" : classAttr.Value.ToString() + " active"); } } }