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

时间:2014-09-05 15:50:12

标签: c# javascript asp.net ajax

我有类别和子类别作为模型。您可能已经猜到,每个类别都包含许多子类别。关键是我有一个视图,在我看来,我有一个像这样的代码段:

<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,但现在我的子类别为值部分我得到了一个文本,表示子类别的名称。

1 个答案:

答案 0 :(得分:0)

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

应该是

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