简体   繁体   English

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

[英]Asp.net Core MVC Dynamically add Select List via JS

I am trying to provide a view where people will be able to create a list of categories and sub categories.我试图提供一个视图,人们可以在其中创建类别和子类别的列表。 Therefore I need to allow users to dynamically add Rows.因此我需要允许用户动态添加行。 Each Row will allow user to add a category and then if they wish a Sub Category.每行将允许用户添加一个类别,然后如果他们希望添加一个子类别。 For the first row I am able to use asp-items attributes to bind to a SelectList in my ViewBag , however when I add a new row via JS I cannot do it, I have tried 2 methods JS (both shown in the code):对于第一行,我可以使用asp-items属性绑定到我的ViewBag中的SelectList ,但是当我通过 JS 添加新行时我不能这样做,我尝试了 2 种 JS 方法(均在代码中显示):

  • 1 - Storing the SelectList in a variable and looping through it 1 - 将 SelectList 存储在变量中并循环遍历它
  • 2 - Setting the asp-items to the SelectList 2 - 将 asp-items 设置为 SelectList

Does anyone know how I can populate my newly added rows?有谁知道我如何填充新添加的行? Also how would I bind the .netred in data to my Model;另外,我如何将数据中的 .netred 绑定到我的 Model; would it have to be done in the controller?是否必须在 controller 中完成?

The code is as follows:代码如下:

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

Used Ajax calls to retrieve Categories data: 使用过的Ajax调用来检索Categories数据:

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

With the server side code looking like: 服务器端代码如下所示:

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

Similar with the last answer but a bit shorter与上一个答案类似但更短

$(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);
        })
    });
});

and on server side在服务器端

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM