1.创建注册数据等
1)Startup.cs
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddHttpContextAccessor(); services.AddTransient<ICountryManager, CountryManager>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseMvc(); } }
2)Model
public class Country { /// <summary> /// 编码 /// </summary> public string Code { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } }
3)Data
using CoreTest.Model; using System.Collections.Generic; namespace CoreTest.Manager { public interface ICountryManager { IEnumerable<Country> GetAll(); } public class CountryManager : ICountryManager { public readonly List<Country> _countryList; public CountryManager() { _countryList = new List<Country> { new Country{ Code="001",Name="China" }, new Country{ Code="002",Name="Japan" }, new Country{ Code="003",Name="USA" }, }; } public IEnumerable<Country> GetAll() { return _countryList; } } }
4)TagHelper的下拉框控件对象
[HtmlTargetElement("country-list")] public class CountryListTagHelper:TagHelper { private readonly ICountryManager _countryManager; public string SelectedValue { get; set; } public CountryListTagHelper(ICountryManager countryManager) { _countryManager = countryManager; } public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "select"; output.Content.Clear(); foreach (var item in _countryManager.GetAll()) { var selected = ""; if (SelectedValue != null && SelectedValue.Equals(item.Code, StringComparison.CurrentCultureIgnoreCase)) { selected = "selected=\"selected\""; } var listItem = $"<option value=\"{item.Code}\" {selected}>{item.Name}</option>"; output.Content.AppendHtml(listItem); } } }
5)页面上的引用
@page @model CoreTest.Pages.EditModel @addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *,CoreTest @{ } <form method="post"> <p> <label>姓名:</label> <input type="text" asp-for="@Model.Input.Name" /> </p> <p> <label>年龄:</label> <input type="number" asp-for="@Model.Input.Age" /> </p> <p> <label>性别:</label> <select asp-for="@Model.Input.Sex"></select> </p> <p> <label>电话号码:</label> <input type="text" asp-for="@Model.Input.Phone" /> </p> <p> <label>国籍:</label> <country-list selected-value="002"></country-list> </p> </form>
效果:
注:
1)Startup记得注册接口服务对象(1.1的红色部分)
2)在单独的页面上使用TagHelperHelper
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
3)使用该项目中所有的TageHelper(@addTagHelper typeName,AssemblyName)
@addTagHelper *,CoreTest
// 方式一,程序集下所有的Taghelper @addTagHelper *,CoreTest // 方式二,明确指定路径 @addTagHelper "CoreTest.CountryListTagHelper,CoreTest" // 方式三,模糊匹配 @addTagHelper "CoreTest.CountryList*,CoreTest"
感谢:https://www.cnblogs.com/hager/p/5817335.html