【问题标题】:how to create a checkboxlist in ASP.Net MVC using jquery如何使用 jquery 在 ASP.Net MVC 中创建复选框列表
【发布时间】:2026-01-24 16:20:05
【问题描述】:

我想根据下拉列表的选定值生成动态复选框。

@Html.DropDownListFor(x => x.Fromsource, new SelectList(Model.Fromsource, "Value", "Key"), "---Select---", new
                    {

                    })
@Html.CheckBox("Tosource", false, new { @class = "dropdown" })
<script>
  $("#Fromsource").change(function () {
            var urlSource = '@Url.Action("FillToSource", "PublishPost")';
            var fromsouyrcetype = $(this).val();
            if (fromsouyrcetype != "") {
                $.ajax({
                    url: urlSource,
                    method: "GET",
                    data: {
                        "sourceType": fromsouyrcetype
                    },
                    success: function (result) {

                        $.each(result, function (index, value) {
                            //what to write here?
                           //value.name = name of the checkbox
                          //value.id = value of the checkbox
                        });
                    }
                });
            } else {


            }

        });</script>

value.idvalue.name 是我想为上面评论中提到的复选框填写的值。

【问题讨论】:

  • 不清楚你想做什么。 - $('#Tosource').empty(); 没有意义(它清除了元素的子元素并且复选框没有任何内容)。您要创建多个复选框吗?
  • 不能接受 List 在您的 FromSource 中?最初,模型中的一个 bool 代表复选框。

标签: jquery asp.net-mvc asp.net-mvc-4 checkboxlist


【解决方案1】:

如果我正确理解您的问题,您希望根据从服务器获得的结果动态创建复选框(每次下拉值更改时都会执行查询):

<div id="checkboxContainer"></div>
<script>
  $("#Fromsource").change(function () {
            var urlSource = '@Url.Action("FillToSource", "PublishPost")';
            var fromsouyrcetype = $(this).val();
            if (fromsouyrcetype != "") {
                $.ajax({
                    url: urlSource,
                    method: "GET",
                    data: {
                        "sourceType": fromsouyrcetype
                    },
                    success: function (result) {
                            $('#checkboxContainer').empty();
                            var content;
                            $.each(result, function (index, value) {
                                content += '<input type="checkbox" name="'+ value.name +'" id="'+value.id+'"/>'
                            });
                            $('#checkboxContainer').html(content);
                        }
                });
            } else {
                $('#checkboxContainer').empty();

            }

        });</script>

【讨论】: