如何在MVC5中同步两个DropDownList元素

本文关键字:两个 DropDownList 元素 MVC5 同步 | 更新日期: 2023-09-27 18:20:58

我有类别和子类别作为模型。每个类别都包括许多子类别,正如你可能已经猜到的那样。重点是,我有一个观点,在我的观点中,我有这样一个代码段:

<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,所以每当我选择一个类别时,我只显示所选类别的子类别。但是,我现在无法提交我的表单,每当我按下提交时,我都会收到一条错误消息,说所选的值不是有效的子类别。我该怎么修?

编辑:

当我使用开发工具进行挖掘时,我发现对于我的Categories,对于值部分,我有数字,这是它们在数据库中的对应id,但现在对于值部分的Subcategories,我得到了一个文本,意思是Subcategory的名称。

如何在MVC5中同步两个DropDownList元素

$("#SubcategoryID").append('<option value="' + subcategory.value + '">' + subcategory.value + '</option>');

应该是

$("#SubcategoryID").append('<option value="' + subcategory.id + '">' + subcategory.value + '</option>');