c# - 使用 Javascript 更改级联 DropDownList 值时 MVC 模型中断

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

我有一个带有模型的 MVC View ,当我从下拉列表中选择某些内容时,它会向我的 Controller 执行 JSON 查询,为第二个下拉列表获取更新的项目列表,并重新填充第二个下拉列表用新的值(value)观打倒。我这样做,但是构建了 <option value="5">Test</option><option value="13">Another</option>....字符串,然后使用新代码设置第二个下拉列表的 HTML:

Javascript:

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

从视觉上看,这运作良好。我的 UI 更新得很好。

但是,当我保存时,它似乎无法识别我创建的第二个下拉菜单的选定值。

一旦我重建了一个最初由 View 模型设置的控件:

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

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

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

<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 中设置“已选择”值,但我并没有设置下拉列表的“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”。

最佳答案

好的,这是一个工作示例。

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

型号

    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; }
    }

Action

   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 Action

这对选定的 id 进行过滤

    [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>

当子类别列表被模型 Binder 拾取时,您选择的选项将在您的帖子中设置。

关于c# - 使用 Javascript 更改级联 DropDownList 值时 MVC 模型中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21040744/

相关文章:

c# - 在 .NET Compact 中模拟曲线图

javascript - 如何处理 $interval is not a function error in angularjs?

javascript - 如何将字符串插入到脚本标签中?

javascript - 单击时下拉切换无法正常工作

c# - 如何将一个 razor 页面包含到另一个 razor 页面?

c# - 在 C# Blazor 的部分类中初始化 RenderFragment

c# - 检索在 Func 中执行的调用方法的名称

javascript - 非数字正则表达式 + 仅允许单个 "."用于输入验证

javascript - d3 js 分层边缘捆绑数据格式

javascript - 手动滚动到 anchor 时更改 url?