javascript - 级联下拉列表不会从数据库加载(MVC、JSON、C#)
问题描述
全部 -
我是 MVC/Javascript 的新手,并尝试了多个教程,了解如何在 MVC 视图上获得适用于州和市的级联下拉列表。我最近的尝试我正在使用这个示例
州从数据库中填充,但城市是一个空白下拉列表,大约有 10 个空白区域。不管我选择什么状态。我错过了什么?感谢您的关注和建议/反馈!
这是数据库表信息:
Regions (contains states): Id (PK Int), Name (Varchar(255) state/regionname), CountryId (Int) Cities (Contains city): Id (PK Int), Name (Varchar(255) state/name), RegionID(int,指向区域表的链接)
这是视图模型:
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>")
});
});
})
});
解决方案
在下面的行中,您在后面缺少一个单引号value=
$("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")
理想情况下,它应该如下所示 -
$("#cityId").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
推荐阅读
- python - 如何在pyspark中保存没有日期的时间信息?
- c# - 在 Bot Framework C# 中启动 OAuth2 对话框后如何中断
- javascript - 如何从 Sheets v4 API 中的 Javascript 作为 JSON 获取 Google 电子表格数据?
- python - AttributeError:“KerasClassifier”对象没有属性“添加”
- python - 在 Python 中部署 bash
- python - 找不到命令:Mac OS 上的 playwright 使用 pip 安装 lib
- jmeter - 如何从 Jmeter 中的数据库中删除一些数据?
- maven - 不可跳过的 Javadoc
- node.js - Firebase 云函数 subscribeToTopic 超时
- ios - 接管 UICollectionView 在 tvOS 上完全滚动