Asp.net Core MVC 通过JS动态添加Select List

Asp.net Core MVC Dynamically add Select List via JS

我正在尝试提供一种视图,人们可以在其中创建类别和子类别列表。因此我需要允许用户动态添加行。 每行将允许用户添加一个类别,然后如果他们希望添加一个子类别。对于第一行,我可以使用 asp-items 属性绑定到我的 ViewBag 中的 SelectList ,但是当我通过 JS 添加新行时我不能这样做,我尝试了 2 种方法 JS(都在代码中显示):

有谁知道如何填充新添加的行?另外,我将如何将数据中的 enetred 绑定到我的模型;是否必须在控制器中完成?

代码如下:

<script type="text/javascript">
    $(document).ready(function () {
        var categories = "@ViewBag.Categories";
        var catOptions = '';
        for (var i = 0; i < categories; i++) {
            catOptions = catOptions + '<option value="' + categories[i].CategoryId + '">' + categories[i].Name + '</option>'
        }

        $(document).on("click", "#btnAddCat", function () {
            var newCat =''+
                '<tr class="categorieRows">' +
                    '<td colspan="2">' +
                '<select>' +
                    catOptions +
                '</select>' +
                    '</td>' +
                    '<td>' +
                        '<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>' +
                    '</td>' +
                '</tr>';
            $('#categoryTable').append(newCat);
        });

        $(document).on("click", "#btnAddSubCat", function () {
            var newSubCat = '' +
                '<tr class="categorieRows">' +
                    '<td></td>' +
                    '<td>' +
                        '<select asp-items="ViewBag.SubCategories"></select>' +
                    '</td>' +
                    '<td></td>' +
                '</tr>';
            $('#categoryTable').append(newSubCat);
        });
    });
</script>
@model IEnumerable<Categories>

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<h4>Surveys</h4>
<hr />
<table class="table table-striped" id="categoryTable">
    <thead>
        <tr>
            <th>
                Category
            </th>
            <th>
                Sub Categories
            </th>
            <th>
                <button type="button" id="btnAddCat" class="btn btn-xs btn-primary classAdd">Add Category</button>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr class="categorieRows">
            <td colspan="2">
                <select asp-items="ViewBag.Categories"></select>
            </td>
            <td>
                <button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>
            </td>
        </tr>
    </tbody>
</table>

<div>
    <a asp-action="Index">Back to List</a>
</div>

已使用 Ajax 次调用来检索类别数据:

<script>
    $(document).ready(function () {
        $(document).on("change", "#selectCategroy", function () {
            var subCat = this;
            $.ajax({
                url: "ReturnJsonSubCategories/?categoryId=" + $(subCat).val(),
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: JSON,
                success: function (result) {
                    var categories = "";
                    $(result).each(function () {
                        categories = categories + '<option value="' + this.subCategoryId + '">' + this.name + '</option>'
                    });

                    var subCateList = $("#selectSubCategroy");
                    subCateList.empty();
                    subCateList.append(categories);
                },
                error: function (data) {
                    return "Error";
                }
            });
        });
    });
</script>

服务器端代码如下所示:

public JsonResult ReturnJsonSubCategories(int categoryId)
    {
        var jsonData = _context.SubCategories.Where(x => x.CategoryId == categoryId).ToList();
        return Json(jsonData);
    }

与上一个答案类似,但更短一些

$(function () {
    $('#CategoryId').change(function () {
        $('#SubCategoryId').empty();
        var url = '@Url.Content("~/")' + "api/CategoryApi/ListSubCategories";
        $.getJSON(url, { categoryId: $('#CategoryId').val() })
            .done(function (data) {
                var subcategories = "";
                $(data).each(function () {
                    subcategories += '<option value="' + this.CategoryId + '">' + this.Title + '</option>'
                });
                $('#SubCategoryId').append(subcategories);
        })
    });
});

在服务器端

    [HttpGet]
    [Route("ListSubCategories")]
    public IActionResult ListSubCategories(int categoryId)
    {
        var subCategories = _categorySvc.ListSubCategories(categoryId);
        return Ok(subCategories);
    }