Reputation: 13
I have a table called country include fields:countryid,countryname,currency in the razor mvc page i want display currency as label after change selected value of country dropdownlist but does not work code? pleass help me tanks
Upvotes: 0
Views: 4248
Reputation: 36645
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:
Upvotes: 1