0

I have this button that when clicked, creates a new div row that contains several dropdowns. How can I populate those dropdowns from the viewmodel that is loaded into my view?

@model App.Data.ViewModels.FilterDocumentsViewModel

<button type="button" class="btn btn-outline-secondary" data-toggle="collapse" data-target="#datatable-search-input-container-rowtwo" aria-expanded="false" aria-controls="datatable-search-input-container-rowtwo">
        <i class="fa fa-plus"></i>
</button>

$("#datatable-search-input-container-rowone-coltwo").on("click", "#add-row", function (e) {
    var htmlElements = "<div class='col-sm-10 row'>";
    htmlElements = htmlElements + "<div class='col-sm-3 search-spacing'>";
    htmlElements = htmlElements + "<label>Document Categories</label>";
    htmlElements = htmlElements + "<select class='form-control' name='CategoryId[]' asp-items='@Model.Categories'>Select Category</select>"
    htmlElements = htmlElements + "<label>Document Fields</label>";
    htmlElements = htmlElements + "<select class='form-control' name='FieldId[]' asp-items='@Model.DocumentFields'>Select Document Fields</select>"
    htmlElements = htmlElements + "</div>";
    htmlElements = htmlElements + "</div>";
    $(htmlElements).appendTo("#datatable-search-input-container-rowone-colone-sub");
    return false;
});

What I have above just creates an empty dropdown list. Also, is it possible to do an onchange for Document Categories that will repopulate Document Fields?

EDIT: Based on @TetsuyaYamamotos answer here is what I made

PartialView:

@model App.Data.ViewModels.FilterDocumentsViewModel
<div class="col-sm-12 row">
    <div class="col-sm-3 search-spacing">
        <label>Document Categories</label>
        @Html.DropDownListFor(m => m.CategoryId, (SelectList)Model.Categories, "Select Category", new { @class = "form-control Categories" })
    </div>
    <div class="col-sm-3 search-spacing">
        <label>Document Fields</label>
        @Html.DropDownListFor(m => m.FieldId, (SelectList)Model.DocumentFields, "Select Field", new { @class = "form-control Fields" })
    </div>
    <div class="col-sm-3 search-spacing">
        <label for="Data">Data</label>
        <input type="text" id="Data" placeholder="Search" />
    </div>
</div>

Jquery:

function refreshDropdown(Input) {
    $.ajax({
            url: "@Url.Action("GetFields", @ViewContext.RouteData.Values["controller"].ToString())",
            method: "POST",
            data: JSON.stringify(Input),
            contentType: "application/json",
            success: function (result) {
                $(".Fields").empty();
                $(".Fields").append("<option value>Select Field</option>");
                $.each(result.fields, function (key, value) {
                    $(".Fields").append("<option value="+value.Id+">"+value.Name+"</option>");
                });
            },
            error: function (error) {
                console.log(error);
            }
        });
}

$("#datatable-search-input-container").on("change", ".Categories", function (e) {
    console.log("changed");
    selected = $(".Categories").find(":selected").val();
    var form_data = selected;
    refreshDropdown(form_data);
    return false;
});

Adding Rows:

$("#datatable-search-input-container-rowone-coltwo").on("click", "#add-row", function (e) {
    $.ajax({
        url: "@Url.Action("AddSearchFilterRow", @ViewContext.RouteData.Values["controller"].ToString())",
        method: "GET",
        contentType: "application/json",
        success: function (result) {
            $(result).appendTo("#datatable-search-input-container-rowone-colone-sub");
        },
        error: function (error) {
            console.log(error);
        }
    });
    return false;
});

The only issue left is that the only onchange that works is the main one and not the jquery added on changes

JianYA
  • 2,750
  • 8
  • 60
  • 136
  • Why not just adding a partial view and use `append()` to add with existing element? Note that `asp-items` is ASP.NET Core helper attribute, it must be created server-side with predefined `select` tag (it rendered as option tags in client-side). – Tetsuya Yamamoto Dec 07 '18 at 07:15
  • @TetsuyaYamamoto your suggestion worked but how can I solve the second issue with the onchange? – JianYA Dec 07 '18 at 08:05

2 Answers2

2

The ASP.NET Core MVC tag helper behavior is similar to @Html.DropDownListFor() helper, they're both rendered server-side and should be treated like asp-for server-side attribute. You need to use partial view containing elements to append, accompanied by a controller action method to return it like below example:

SelectPartialView.cshtml

@model App.Data.ViewModels.FilterDocumentsViewModel

<div class='col-sm-10 row'>
   <div class='col-sm-3 search-spacing'>
       <label>Document Categories</label>
       <select class='form-control category' asp-for='CategoryId' asp-items='@Model.Categories'>Select Category</select>
       <label>Document Fields</label>
       <select class='form-control field' asp-for='FieldId' asp-items='@Model.DocumentFields'>Select Document Fields</select>
   </div>
</div>

Controller Action

public IActionResult GetSelectList()
{
    // do something
    return PartialView("SelectPartialView");
}

Then use AJAX callback to append partial view elements into target element:

$("#datatable-search-input-container-rowone-coltwo").on("click", "#add-row", function (e) {
    $.get('@Url.Action("GetSelectList", "ControllerName")', function (result) {
        $("#datatable-search-input-container-rowone-colone-sub").append(result);
    });
});

Regarding cascading <select> tag helper, you need to define class selector into both dropdowns and use AJAX to populate option list:

$('.category').on('change', function() {
    $.ajax({
       type: 'GET',
       url: '@Url.Action("GetFields", "ControllerName")',
       data: { CategoryId: $(this).val() },
       success: function (result) {
           $('.field').empty();
           $.each(result, function (i, item) {
               // replace 'item.Value' and 'item.Text' from corresponding list properties into model class
               $('.field').append('<option value="' + item.Value + '"> ' + item.Text + ' </option>');
           });
       },
       error: function (xhr, status, err) {
           // error handling
       }
    });
});

Controller Action

public IActionResult GetFields(int CategoryId)
{
    // populate SelectListItem here
    return new JsonResult(list);
}

Another example of cascading <select> element can be found here:

ASP.NET MVC Core Cascading DropDownList

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
0

You can get the data from viewmodel into a javascript object and Loop through that data using jquery

var modelCategories = @Html.Raw(Json.Encode(Model.Categories));
var modelDocumentFields =@Html.Raw(Json.Encode(Model.DocumentFields)); 
$("#datatable-search-input-container-rowone-coltwo").on("click", "#add-row", function (e) {
    var htmlElements = "<div class='col-sm-10 row'>";
    htmlElements = htmlElements + "<div class='col-sm-3 search-spacing'>";
    htmlElements = htmlElements + "<label>Document Categories</label>";
    htmlElements = htmlElements + "<select class='form-control' name='CategoryId[]'>;
    htmlElements += "<option>Select Category</option>";
    $.each(modelCategories, function(i,v){
       htmlElements += `<option value="${v.CategoryId}">${v.CategoryName}</option>`
    });

    htmlElements = htmlElements + "</select>";
    htmlElements = htmlElements + "<label>Document Fields</label>";
    htmlElements = htmlElements + "<select class='form-control' name='FieldId[]'>;
    htmlElements += "<option>Select Document Fields</option>";
    $.each(modelCategories, function(i,v){
       htmlElements += `<option value="${v.FieldId}">${v.FieldNameName}</option>`
    });
    htmlElements = htmlElements + "</select>";
    htmlElements = htmlElements + "</div>";
    htmlElements = htmlElements + "</div>";
    $(htmlElements).appendTo("#datatable-search-input-container-rowone-colone-sub");
    return false;
});
zetawars
  • 1,023
  • 1
  • 12
  • 27