Asp.Net MVC与Razor级联DropdownList
问题描述:
我试图有一对级联下拉,缩小基于选定状态的城市列表。到目前为止,我有这样的: 查看:Asp.Net MVC与Razor级联DropdownList
<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);
}
在我的拉链码模型我有拉链,primary_city和状态。在CollLocation中,我希望只能看到stateCol下拉列表中选中状态的引用。这两个下拉菜单对我来说都很有用,但是,它们不能一起工作。我尝试了其他的教程和答案,但他们只是让我更抓挠我的头。任何帮助将不胜感激。
答
您每次更改状态下拉菜单时都需要发出Ajax请求。因此,当状态下拉更改时,JavaScript函数应向您的控制器发出Ajax请求以查询您想要的Zipcode。
您可以下载我的项目在Github上,并看看2个文件 “\查看\ ClientOrder \ Create.cshtml” 和 “\ RiceStoreScripts \ ClientOrder.js”
推荐你学习代码[此DotNetFiddle](https://dotnetfiddle.net/1bPZym) - 您需要ajax才能正常工作,但您的代码还存在其他多种问题 –
非常感谢。这是一个很好的小提琴。它帮助并清除了我的很多问题 – TomBB