[英]How to synchronize two DropDownList elements in MVC5?
我有类别和子类别作为模型。 您可能已经猜到,每个类别都包含许多子类别。 关键是我有一个视图,并且在我的视图中,我有一个像这样的代码段:
<div class="form-group">
@Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CategoryID", null, "Please select a category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SubcategoryID, "Subcategory", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("SubcategoryID", null, "Please select a subcategory", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.SubcategoryID, "", new { @class = "text-danger" })
</div>
</div>
然后,在我的控制器中,我有两个ViewBag对象,这些对象填充了我的SelectList对象:
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
ViewBag.SubcategoryID = new SelectList(db.Subcategories, "SubcategoryID", "SubcategoryName");
然后,我编写了一些AJAX代码,以使DropDownList元素的值同步。 我有以下动作和JS代码。
[AllowAnonymous]
public JsonResult GetSubcategories(int id)
{
var results = db.Subcategories.Where(s => s.CategoryID == id).Select(x => new { id = x.SubcategoryID, value = x.SubcategoryName }).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
带有AJAX调用的JavaScript代码:
$("#CategoryID").change(function () {
$("#SubcategoryID").empty();
$.ajax({
type: 'POST',
url: '/Account/GetSubcategories',
dataType: 'json',
data: { id: $("#CategoryID").val() },
success: function (subcategories) {
$.each(subcategories, function (i, subcategory) {
$("#SubcategoryID").append('<option value="' + subcategory.value + '">' + subcategory.value + '</option>');
});
},
error: function (ex) {
console.log('Failed to retrieve subcategories! ' + ex);
}
});
return false;
});
关键是,它同步了DropDownLists,因此,每当我选择一个类别时,我只会显示该所选类别的子类别。 但是,我现在无法提交表单,每当我按提交时,我都会收到一条错误消息,指出所选值不是有效的子类别。 我该如何解决?
编辑:
当我使用开发人员工具进行挖掘时,我看到对于我的类别,对于价值部分,我有数字,这是它们在数据库中的对应ID,但是现在对于价值部分的子类别,我得到了一个文本,这意味着子类别的名称。
这个
$("#SubcategoryID").append('<option value="' + subcategory.value + '">' + subcategory.value + '</option>');
应该
$("#SubcategoryID").append('<option value="' + subcategory.id + '">' + subcategory.value + '</option>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.