使用Javascript更改级联DropDownList值时,MVC模型会中断

时间:2014-01-10 09:40:09

标签: c# javascript jquery asp.net asp.net-mvc

我有一个模型的MVC视图,当我从下拉列表中选择一些东西时,它会向我的控制器执行JSON查询,获取第二个下拉列表的更新项目列表,并重新填充第二个下拉列表新的价值观。我这样做,但构建<option value="5">Test</option><option value="13">Another</option>....字符串,然后使用新代码设置第二个下拉列表的HTML:

使用Javascript:

$(".cmbSubCategory").html(result.SubCategoryString);

从视觉上看,这很有效。我的UI很好地更新了。

然而,当我保存时,它似乎无法识别第二个下拉列表的选定值,这是我建立的那个。

重建控件后,最初由视图模型设置:

@Html.DropDownListFor(x => x.SubCategoryId, Model.SubCategories, new { @class = "cmbSubCategory form-control" })

..当我将“发布”回到我的控制器时,我是否可以不再使用模型中的选定值?

我注意到即使在视觉上,第二个下拉列表也会填充一些选项,当我'查看页面来源'时,它只显示:

<select class="cmbSubCategory form-control" data-val="true" data-val-number="The field SubCategoryId must be a number." data-val-required="The SubCategoryId field is required." id="SubCategoryId" name="SubCategoryId"><option value="0">Select a Category</option>
</select>

没有选项..但在浏览器中,它显示了项目......

编辑:发现问题!

虽然我正在填充HTML并在HTML中设置'Selected'值,但我没有设置下拉列表的'val'!

这现在有效:

if (result.Success == 'true') {
                    if (result.SubCategoryString != "") {
                        $('#cmbType').val(result.TransactionTypeId);
                        $('#cmbCategory').val(result.CategoryId);
                        $(".cmbSubCategory").html(result.SubCategoryString);
                        $(".cmbSubCategory").val(result.SubCategoryId);
                    }
                }

最后一行是关键! $(".cmbSubCategory").val(result.SubCategoryId);

我认为构建HTML Selected选项已足够 - 但您还必须设置组合的'val'。

1 个答案:

答案 0 :(得分:2)

好的,这是一个有效的例子。

请注意,硬编码值仅用于演示目的。

<强>模型

    public class FooModel
    {
        public int CategoryId { get; set; }
        public int SubCategoryId { get; set; }
        public List<Category> Categories { get; set; }
        public List<SubCategory> SubCategories { get; set; }
    }

    public class Category
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }

    public class SubCategory
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public int CategoryId { get; set; }
    }

操作

   public ActionResult Ddl()
    {
        var model = new FooModel();
        var categories = new List<Category>();
        var subCategories = new List<SubCategory>();

        // Read from db
        categories.Add(new Category { Id = 1, Description = "Cat 1" });
        categories.Add(new Category { Id = 2, Description = "Cat 2" });
        subCategories.Add(new SubCategory { Id = 1, Description = "Sub-Cat 1", CategoryId = 1 });
        subCategories.Add(new SubCategory { Id = 2, Description = "Sub-Cat 2", CategoryId = 2 });

        model.Categories = categories;
        model.SubCategories = subCategories.Where(s => s.Id == 1).ToList();

        // initially set selected
        model.CategoryId = 1;
        model.SubCategoryId = 1;

        return View(model);
    }

    [HttpPost]
    public ActionResult Ddl(FooModel model)
    {
        var subCategoryId = model.SubCategoryId;

        // Send categories back to model etc
        ...

        return View(model);
    }

Json行动

这会过滤所选内容

    [HttpGet]
    public ActionResult GetSubCategories(int id)
    {
        var subCategories = new List<SubCategory>();
        subCategories.Add(new SubCategory { Id = 1, Description = "Sub-Cat 1", CategoryId = 1 });
        subCategories.Add(new SubCategory { Id = 2, Description = "Sub-Cat 2", CategoryId = 2 });
        var filteredCategories = subCategories.Where(s => s.Id == id).ToList();
        return Json(filteredCategories, JsonRequestBehavior.AllowGet);
    }

查看

这只是为类别设置onchange事件,将事件加载到子类别列表中。

@model FooModel

@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.CategoryId, new SelectList(Model.Categories.AsEnumerable(), "Id", "Description"))
    @Html.DropDownListFor(m => m.SubCategoryId,new SelectList(Model.SubCategories.AsEnumerable(), "Id", "Description"))
    <input type="submit" value="submit" />
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
    var getsubCategoryUrl = '@Url.Action("GetSubCategories")';
    $(function () {

        $('#CategoryId').change(function () {
            var selectedCategory = $('#CategoryId').val();
            if (selectedCategory != null) {
                $.getJSON(getsubCategoryUrl, { id: selectedCategory }, function (subs) {

                    var subSelect = $('#SubCategoryId');
                    subSelect.empty();

                    $.each(subs, function (index, sub) {
                        subSelect.append($('<option/>', {
                            value: sub.Id,
                            text: sub.Description
                        }));
                    });

                });
            }
        });

    });
</script>

当模型活页夹选取子类别列表时,您的选项将在帖子中设置。