ASP.NET Core 5.0 MVC 如何获取DropDownList选中的国家值
实现方案
1. 定义强类型模型
按照需求将国家列表定义为模型公共属性,同时新增属性存储用户选中的国家值:
public class CountryViewModel { // 存储下拉列表选项集合 public IEnumerable<SelectListItem> CountryList { get; set; } // 存储用户选中的国家值 public string SelectedCountry { get; set; } }
2. 控制器GET请求逻辑
将原有的国家列表生成逻辑填充到模型属性中,不再依赖ViewBag传递数据:
public IActionResult Index() { List<string> countryNameList = new List<string>(); CultureInfo[] cInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures); foreach (CultureInfo cInfo in cInfoList) { RegionInfo r = new RegionInfo(cInfo.LCID); if (!countryNameList.Contains(r.EnglishName)) { countryNameList.Add(r.EnglishName); } } countryNameList.Sort(); var viewModel = new CountryViewModel { CountryList = countryNameList.Select(x => new SelectListItem { Text = x, Value = x }) }; return View(viewModel); }
3. 视图渲染逻辑
使用强类型绑定渲染下拉列表,不需要额外拼接字段名:
@model CountryViewModel <select asp-for="SelectedCountry" asp-items="Model.CountryList" class="form-control"> <option value="">请选择国家</option> </select>
如果习惯使用HtmlHelper可以用以下写法:
@Html.DropDownListFor(m => m.SelectedCountry, Model.CountryList, "请选择国家", new { @class = "form-control" })
4. 控制器读取选中值逻辑
提交请求时直接从模型属性中读取选中值即可,不需要额外处理表单字段:
[HttpPost] public IActionResult Index(CountryViewModel viewModel) { // 直接获取选中的国家值 string selectedCountry = viewModel.SelectedCountry; if (ModelState.IsValid) { // 此处编写业务逻辑 } // 回发时重新填充国家列表,避免视图渲染报错 viewModel.CountryList = GetCountryList(); return View(viewModel); } // 可将国家列表生成逻辑抽为公共方法,复用代码 private IEnumerable<SelectListItem> GetCountryList() { List<string> countryNameList = new List<string>(); CultureInfo[] cInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures); foreach (CultureInfo cInfo in cInfoList) { RegionInfo r = new RegionInfo(cInfo.LCID); if (!countryNameList.Contains(r.EnglishName)) { countryNameList.Add(r.EnglishName); } } countryNameList.Sort(); return countryNameList.Select(x => new SelectListItem { Text = x, Value = x }); }
说明:该方案为ASP.NET Core MVC的标准最佳实践,使用强类型绑定避免了ViewBag的动态类型风险,编译阶段即可检查错误,完全符合你要求的通过模型属性传递、读取国家列表相关数据的需求,不需要像ASP.NET Web Form那样依赖服务端控件的AutoPostBack事件。
内容的提问来源于stack exchange,提问作者dark.vador
相关产品推荐
相关产品推荐

