首页 > 解决方案 > 从 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为公共属性,以便能够通过控制器的方法检索任何选定的国家/地区。

最好的

标签: c#asp.net-mvcasp.net-coreasp.net-core-tag-helpers

解决方案


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>
    }

结果: 在此处输入图像描述


推荐阅读