javascriptasp.net-coreasp.net-core-mvcasp.net-core-2.0selectlistitem

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

Does anyone know how I can populate my newly added rows? Also how would I bind the enetred in data to my Model; would it have to be done in the 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>


Solution

  • Used Ajax calls to retrieve Categories data:

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