首页 > 解决方案 > asp .net core mvc中下拉列表的选定值

问题描述

我在 razor mvc 页面中有一个名为 country 的表,包括字段:countryid、countryname、currency 我想在更改国家下拉列表的选定值后将货币显示为标签,但代码不起作用?请帮我坦克

标签: asp.net-core-mvc

解决方案


Here is a whole working demo you could follow:

Model:

public class Country
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
    public string Currency { get; set; }
}

View(Index.cshtml):

@model Country
<div class="form-group">
    <label asp-for="CountryName" class="control-label"></label>
    <select id="CountryList" asp-for="CountryName" class="form-control" asp-items="@ViewBag.Country">
        <option>Select a Country</option>
    </select>
</div>
<div id="DisplayCurrency"></div>
@section Scripts
{
    <script>
        $("#CountryList").change(function () {
            var v = $(this).val();
            $.getJSON("/Home/GetCurrency?countryName=" + v, function (data) {
                console.log(data);
                $("#DisplayCurrency").append('<label>' + data+'</label>');
                
            });
        });
    </script>
}

Controller:

public class HomeController : Controller
{
    List<Country> countryList = new List<Country>()
    {
        new Country(){CountryId=1,CountryName="China",Currency="¥"},
        new Country(){CountryId=2,CountryName="US",Currency="$"},
        new Country(){CountryId=3,CountryName="EUR",Currency="£"}
    };

    public IActionResult Index()
    {
        ViewBag.Country = new SelectList(countryList, "CountryName", "CountryName");
        return View();
    }
    public IActionResult GetCurrency(string countryName)
    {
        var currency = countryList.Where(c => c.CountryName == countryName)
                                   .Select(c => c.Currency).FirstOrDefault();
        return Json(currency);
    }
}

Result:

enter image description here


推荐阅读