public static void AddCssClass(this TagHelperAttributeList attributeList, string cssClass) { const string classAttribute = "class"; var existingCssClassValue = attributeList .FirstOrDefault(x => x.Name == classAttribute)?.Value.ToString(); // If the class attribute doesn't exist, or the class attribute // value is empty, just add the CSS class to class attribute if (String.IsNullOrEmpty(existingCssClassValue)) { attributeList.SetAttribute(classAttribute, cssClass); } // Here I use Regular Expression to check if the existing css class // value has the css class already. If yes, you don't need to add // that css class again. Otherwise you just add the css class along // with the existing value. // \b indicates a word boundary, as you only want to check if // the css class exists as a whole word. else if (!Regex.IsMatch(existingCssClassValue, $@"\b{ cssClass }\b", RegexOptions.IgnoreCase)) { attributeList.SetAttribute(classAttribute, $"{ cssClass } { existingCssClassValue }"); } }
public static void Merge(this TagHelperAttributeList attributes, string name, object value) { var attr = attributes.FirstOrDefault(a => a.Name == name); if (attr != null) { attributes.Remove(attr); } attributes.Add(name, $"{value} {attr?.Value}"); }
protected virtual void SetHrefAttribute(string currentPage, TagHelperAttributeList attributeList) { var hrefAttribute = attributeList.FirstOrDefault(x => x.Name.Equals("href", StringComparison.OrdinalIgnoreCase)); if (hrefAttribute != null) { var pageUrl = TagHelper.Model.PageUrl; var routeValue = $"currentPage={currentPage}{(TagHelper.Model.Sort.IsNullOrWhiteSpace()? "" : "&sort="+TagHelper.Model.Sort)}"; pageUrl += pageUrl.Contains("?") ? "&" + routeValue : "?" + routeValue; attributeList.Remove(hrefAttribute); attributeList.Add(new TagHelperAttribute("href", pageUrl, hrefAttribute.ValueStyle)); } }
public static void Merge(this TagHelperAttributeList attributes, string name, string value) { if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } var curr = attributes.FirstOrDefault(att => string.Equals(att.Name, name, StringComparison.Ordinal)); if (curr == null) { attributes.Add(name, value); } else { attributes.Remove(curr); attributes.Add(name, $"{curr.Value} {value}"); } }