CountryTagHelper–part 2
Finally, I have arrived at functionality. I said that I want something like
<select asp-country="true" asp-country-selected="US" >
</select>
The functionality is very easy to be added:
The entire class is :
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Localization; using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace CTHWeb.Controllers { [HtmlTargetElement( "select" , Attributes = ASPCountryAttributeName)] public class CountryTagHelper:TagHelper { private const string ASPCountryAttributeName = "asp-country" ; private const string ASPCountrySelectedAttributeName = "asp-country-selected" ; [HtmlAttributeName(ASPCountryAttributeName)] public bool ASPCountry { get ; set ; } [HtmlAttributeName(ASPCountrySelectedAttributeName)] public string ASPCountrySelected{ get ; set ; } static string [] CountryISO; //static PropertyInfo[] properties; static CountryTagHelper() { var t = typeof ( ResCTH); var properties= t.GetProperties( BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty); CountryISO = properties .Where(it=>it.Name.Length==2) .Select(it => it.Name) .ToArray(); } public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (ASPCountry) { bool existSelected = ! string .IsNullOrWhiteSpace(ASPCountrySelected); string option = "<option value='{0}' {2}>{1}</option>" ; foreach ( var item in CountryISO) { string selected = "" ; string localizedName = ResCTH.ResourceManager.GetString(item); if (existSelected) { bool currentItem = string .Equals(item, ASPCountrySelected, StringComparison.CurrentCultureIgnoreCase); currentItem = currentItem || string .Equals(localizedName, ASPCountrySelected, StringComparison.CurrentCultureIgnoreCase); if (currentItem) selected = "selected" ; } output.Content.AppendFormat(option, item, localizedName,selected); } } return base .ProcessAsync(context, output); } } } |
The important thing is that it works with other html attributes, like
<select asp-country="true" asp-country-selected="US" disabled=”disabled”>
</select>
What it remains to be done:
- from IP – recognize the country of the visitor from IP
- localized – display messages in other language
- first item empty – now it selects Andorra
- Add select2 with image flags
- NuGet package
- readme.md / wiki on github
- tests
Leave a Reply