asp.net-core-mvc - asp .net core mvc中下拉列表的选定值
问题描述
我在 razor mvc 页面中有一个名为 country 的表,包括字段:countryid、countryname、currency 我想在更改国家下拉列表的选定值后将货币显示为标签,但代码不起作用?请帮我坦克
解决方案
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:
推荐阅读
- ios - 有没有办法查看 WKWebView 何时可以使用 HTTPCookie?
- mysql - mysql #1054 使用 phpmyadmin 的未知列
- swift - 从 Firebase Firestore DB SWIFT UI 读取数据
- reactjs - 如何使用 React 获取目录中所有文件的名称列表?
- google-apps-script - 将 Google 工作表导出为 PDF 设置参数,例如边距
- python - Camelot-py 没有在一行中检测到两行文本
- mysql - 无法在 MacOS 上启动 mysql 8.0 docker 映像
- react-admin - React Admin:保持并清除提交时的创建表单
- python - [Python]-与 ie VS Code 相比,为什么在没有“print()”函数的终端上打印输出?
- css - 如何使容器在 Flex 上居中?