我正在尝试使用一对级联下拉菜单,根据选定状态缩小城市列表范围。到目前为止我有这个: 查看:
<div class="form-group">
@Html.LabelFor(model => model.CollLocation, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-6">
@Html.DropDownList("stateCol", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Select a state")
@Html.ValidationMessageFor(model => model.CollLocation, "", new { @class = "text-danger" })
</div>
<div class="col-md-6">
@Html.DropDownList("CollLocation", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Select a city")
@Html.ValidationMessageFor(model => model.CollLocation, "", new { @class = "text-danger" })
</div>
这个控制器:
// GET: Coll/Create
public ActionResult Create()
{
var stateColl = db.ZipCodes.OrderBy(c => c.state).Select(c => c.state).Distinct();
var cityCol = db.ZipCodes.Select(C => C.primary_city).Distinct();
ViewBag.stateCol = new SelectList(stateColl);
ViewBag.ArRecID = new SelectList(db.ArRecs, "ArRecID", "ArZipID");
ViewBag.CollLocation = new SelectList(cityCol);
return View();
}
// POST: Coll/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CollID,ArRecID,CollName,CollDescr,CollValue,CollOwner,CollLocation,DateCreated,ModBy,ModDate,CreatedBy")] Collateral collateral)
{
if (ModelState.IsValid)
{
db.Coll.Add(coll);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ArRecID = new SelectList(db.ArRecs, "ArRecID", "ArZipID", coll.ArRecID);
ViewBag.CollLocation = new SelectList(db.ZipCodes, "zip", "primary_city", coll.CollLocation).Distinct();
return View(collateral);
}
在我的ZipCodes模型中,我有zip,primary_city和state。在CollLocation中,我希望只能看到stateCol下拉列表中所选状态的引用。这两个下降对我来说都有用,但它们并没有合作。我尝试了其他教程和答案,但是他们只是让我更加头疼。任何帮助将不胜感激。
答案 0 :(得分:0)
每次更改状态下拉列表时,都需要发出Ajax请求。因此,当State下拉列表发生更改时,JavaScript函数应向您的控制器发出Ajax请求,以查询您想要的Zipcode。
您可以在Github下载我的项目并查看2个文件“\ Views \ ClientOrder \ Create.cshtml”和“\ RiceStoreScripts \ ClientOrder.js”