Я пытаюсь обновить 2 зависимых раскрывающихся списка одновременно на основе значения основного раскрывающегося списка. Возможно ли, если да, что не так в моем коде? Исправьте, пожалуйста.
Может быть, лучше использовать ASP. NET возможности каскадного выпадающего списка? Если да, как это сделать с 3 раскрывающимися списками?
Просмотр
@model RKB.Models.CountryStateViewModel
<br /><br/>
@using (Html.BeginForm("Index", "Home"))
{
<div class="container">
<div class="form-group">
@if (ViewBag.CountryList != null)
{
@Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "Выберите страну", new { @class = "form-control" })
}
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.StateId, new SelectList(" "), "Выберите штат", new { @class = "form-control" })
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.PriceId, new SelectList(" "), "Выберите цену", new { @class = "form-control", @style = "display:none" })
</div>
<button type="submit">Send</button>
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.PriceId + "'>" + row.Price1 + "</option>")
});
});
})
});
</script>
Контроллер
public class HomeController : Controller
{
RKBEntities db = new RKBEntities();
public ActionResult Index()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryStateViewModel csm)
{
return View();
}
public JsonResult GetStateList(int CountryId)
{
db.Configuration.ProxyCreationEnabled = false;
List<State> StateList = db.States.Where(x => x.CountryId == CountryId).ToList();
return Json(StateList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPriceList(int StateId)
{
db.Configuration.ProxyCreationEnabled = false;
List<Price> PriceList = db.Prices.Where(x => x.StateId == StateId).ToList();
return Json(PriceList, JsonRequestBehavior.AllowGet);
}
}