c# - 从 ASP.NET Core 5.0 MVC DropDownList 中获取选定的国家
问题描述
尊敬的社区成员
在线搜索有关在 ASP.NET Core MVC 中使用cultureinfo 绑定国家/地区列表
更新Controller
感谢以下代码确实有帮助:
List<string> CountryList = new List<string>() ;
CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
foreach (CultureInfo CInfo in CInfoList)
{
RegionInfo R = new RegionInfo(CInfo.LCID);
if (!(CountryList.Contains(R.EnglishName)))
{
CountryList.Add(R.EnglishName);
}
}
CountryList.Sort();
ViewBag.CountryList = CountryList;
return View();
结合以下Tag Helper
来自View
:
@Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList), "Select a country", new
{@class = "form-control" })
但是,我想知道如何Get
/Read 所选国家/地区的价值,仍然通过Controller's method
. 我想到首先定义Model
如下public property
:
public IEnumerable <SelectListItem> countryList {
get;
set;
}
但我很想知道通过Model
.
注意:在ASP.NET
我过去常常通过以下方式实现这样的要求:
string example = testid.SelectedItem.Text;
添加事件后
<asp:DropDownList ID="testid" runat="server" CssClass="form-control"
OnSelectedIndexChanged="test_event" AppendDataBoundItems="true" AutoPostBack="true">
</asp:DropDownList>
任何相关的反馈将不胜感激。
注意:理想的解决方案应包括将CountryList
(例如countrylist
)in定义Model
为公共属性,以便能够通过控制器的方法检索任何选定的国家/地区。
最好的
解决方案
If you want to get the selected value in controller,you can try to use a form,when the selected item change,pass the selected value to controller,here is a demo:
行动:
public IActionResult TestCountryList(string CountryList)
{
List<string> countryList = new List<string>();
CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
foreach (CultureInfo CInfo in CInfoList)
{
RegionInfo R = new RegionInfo(CInfo.LCID);
if (!(countryList.Contains(R.EnglishName)))
{
countryList.Add(R.EnglishName);
}
}
countryList.Sort();
ViewBag.CountryList = countryList;
return View();
}
测试国家列表视图:
<form id="myform" method="post">
@Html.DropDownList("CountryList", new SelectList(ViewBag.CountryList), "Select a country", new
{ @class = "form-control" })
</form>
@section scripts
{
<script>
$("#CountryList").change(function () {
$("#myform").submit();
})
</script>
}
推荐阅读
- python - Is this a circular import?
- c# - I have an issue with a contact form. Works on localhost. When deployed its giving error when attempting to post it via the submit button
- java - Make recursive API call using Retrofit
- javascript - Reactjs 变量在 useEffect 之后返回未定义
- python - 如何显示图像并在 1.5 秒后将其杀死?
- vue.js - Vue 3:将 Options API 组件转换为 Composition API(将容器设置为元素 - this.$el vs ref?)
- blockchain - 为什么我的以太坊智能合约交易在 X 笔交易后没有显示?
- c++ - 这个递归案例有什么问题?
- vapor-fluent - 如何使用 Vapor 添加约束?
- python - Python 调度器说明