.NET Core开发单选框触发GET API实现数据库过滤填充下拉框求代码骨架
实现步骤与代码骨架
1. 后端 .NET Core API 部分
1.1 定义数据模型
创建关联的国家和州/省模型,映射数据库表结构:
// Country.cs public class Country { public int Id { get; set; } public string Name { get; set; } public ICollection<State> States { get; set; } } // State.cs public class State { public int Id { get; set; } public string Name { get; set; } public int CountryId { get; set; } public Country Country { get; set; } }
1.2 数据库上下文(DbContext)
用EF Core操作数据库,添加测试用的种子数据:
// AppDbContext.cs using Microsoft.EntityFrameworkCore; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Country> Countries { get; set; } public DbSet<State> States { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // 初始化测试数据 modelBuilder.Entity<Country>().HasData( new Country { Id = 1, Name = "United States" }, new Country { Id = 2, Name = "Canada" } ); modelBuilder.Entity<State>().HasData( new State { Id = 1, Name = "California", CountryId = 1 }, new State { Id = 2, Name = "Texas", CountryId = 1 }, new State { Id = 3, Name = "Ontario", CountryId = 2 }, new State { Id = 4, Name = "Quebec", CountryId = 2 } ); } }
1.3 API控制器
创建控制器提供GET接口,根据国家ID返回对应州/省数据:
// StatesController.cs using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; [Route("api/[controller]")] [ApiController] public class StatesController : ControllerBase { private readonly AppDbContext _context; public StatesController(AppDbContext context) { _context = context; } // GET: api/States?countryId=1 [HttpGet] public async Task<ActionResult<IEnumerable<object>>> GetStates(int countryId) { var states = await _context.States .Where(s => s.CountryId == countryId) .Select(s => new { s.Id, s.Name }) // 只返回必要字段,减少数据传输 .ToListAsync(); if (states.Count == 0) { return NotFound(); } return Ok(states); } }
1.4 数据库配置
在Program.cs中注册DbContext:
// Program.cs builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
在appsettings.json添加数据库连接字符串:
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CountryStateDb;Trusted_Connection=True;MultipleActiveResultSets=true" } }
执行数据库迁移命令(Package Manager Console中):
Add-Migration InitialCreate Update-Database
2. 前端部分
2.1 HTML结构
包含单选框组和州/省下拉框:
<div> <h3>选择国家</h3> <input type="radio" name="country" value="1" id="us"> <label for="us">United States</label><br> <input type="radio" name="country" value="2" id="canada"> <label for="canada">Canada</label><br> <h3>State/Province(州/省)</h3> <select id="stateSelect"> <option value="">请先选择国家</option> </select> </div>
2.2 JavaScript逻辑
监听单选框变化,自动调用API填充下拉框:
const countryRadios = document.querySelectorAll('input[name="country"]'); const stateSelect = document.getElementById('stateSelect'); countryRadios.forEach(radio => { radio.addEventListener('change', async function() { if (this.checked) { const countryId = this.value; try { const response = await fetch(`/api/States?countryId=${countryId}`); if (!response.ok) throw new Error('请求失败'); const states = await response.json(); // 清空下拉框原有内容 stateSelect.innerHTML = '<option value="">请选择州/省</option>'; // 添加新选项 states.forEach(state => { const option = document.createElement('option'); option.value = state.Id; option.textContent = state.Name; stateSelect.appendChild(option); }); } catch (err) { console.error('加载州数据出错:', err); stateSelect.innerHTML = '<option value="">加载失败,请重试</option>'; } } }); });
内容的提问来源于stack exchange,提问作者Aman Singh
相关产品推荐
相关产品推荐

