【发布时间】:2020-09-11 09:27:17
【问题描述】:
全部 -
我是 MVC/Javascript 的新手,并尝试了多个教程,了解如何在 MVC 视图上获得适用于州和城市的级联下拉列表。我最近的尝试是使用这个Example
州从数据库中填充,但城市是一个空白下拉列表,大约有 10 个空白区域。不管我选择什么状态。我错过了什么?感谢您的关注和建议/反馈!
这是数据库表信息:
区域(包含状态):Id (PK Int)、Name (Varchar(255) state/regionname)、CountryId (Int) Cities(包含城市):Id (PK Int)、Name (Varchar(255) state/name)、RegionID (int, linkes to region table)
这是视图模型:
public class UserAds
{
public int addId { get; set; }
public int userCreatedAcctId { get; set; }
public string userForAccEmail { get; set; }
public string photoFileLocation { get; set; }
public string addTitle { get; set; }
public string addDesc { get; set; }
public string addPersonalityTraits { get; set; }
public string addHobbies { get; set;}
[Required]
[Display(Name = "State / Region")]
public int stateId { get; set; }
[Required]
[Display(Name = "City")]
public int cityId { get; set; }
}
这里是控制器:
[HttpGet]
public ActionResult CreateAd()
{
List<Region> stateList = db.Regions.ToList();
ViewBag.StateList = new SelectList(stateList, "Id", "Name");
return View();
}
public JsonResult GetCitiesList(int StateId)
{
db.Configuration.ProxyCreationEnabled = false;
List<City> CityList = db.Cities.Where(x => x.RegionId == StateId).ToList();
return Json(CityList, JsonRequestBehavior.AllowGet);
}
观点:
<div class="container">
<div class="form-group">
@if (ViewBag.StateList != null)
{
@Html.DropDownListFor(model => model.stateId, ViewBag.StateList as SelectList, "--Select State--", new { @class = "form-control" })
}
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.cityId, new SelectList(" "), "--Select City--", new { @class = "form-control" })
</div>
javascript
<script>
$(document).ready(function () {
$("#stateId").change(function () {
$.get("GetCitiesList", { StateId: $("#stateId").val() }, function (data) {
$("#cityId").empty();
$.each(data, function (index, row) {
$("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")
});
});
})
});
【问题讨论】:
标签: javascript json asp.net-mvc cascadingdropdown