Hawke
Hawke

Reputation: 584

Populating a select dynamically using C sharp object

I have a list of custom objects (Book) and I want a second select box to populate based on the tile selected in the first dropdown. I have seen many answers on how to do this with statically typed lists, but not ones from an asp.net object.

public class Book
{

    public string Title { get; set; }

    public List<string> Chapter { get; set; }

}

Model.books is a list of Book objects above.

In cshtml:

<div class="form-group">
                        <label asp-for="Book.Title" class="control-label">Title</label>
                        <select id="title-select" asp-for="Book.Title" class="form-control">
                            @foreach (var item in Model.books)
                            {
                                <option value="@item">
                                    @Html.DisplayFor(modelItem => item.Title)
                                </option>
                            }
                        </select>
                    </div>

<div class="form-group">
                        <label asp-for="Book.Chapter" class="control-label">Chapter</label>
                        <select id="chapter-select" asp-for="Book.Chapter" class="form-control">
                            @foreach (var item in chapters?)
                            {
                                //Chapter select based on Title chosen above
                            }
                        </select>
                    </div>

JQuery:

    $('#title-select').on('change', function () {
        var value = this.value

//How to pass the book.chapter object into here to populate the dropdown list


    });

There are not many books or chapters so it might be worth just passing all the books rather than using Ajax? I am mostly unsure how to get my Books list to the JQuery in the first place (I am not used to web dev).

Upvotes: 0

Views: 358

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can store the book title associated with chapter as data-* attribute for option element in chapters dropdown.

@foreach (var book in Model.books)
    @foreach (var item in book.Chapter)
      {
         <option data-book-title="@book.Title">@item</option>
      }
}

Then use the value of selected book element in book dropdown to filter chapters that matches data attribute to enable them:

$('#title-select').on('change', function () {
  var bookValue = this.value;
  $('#chapter-select option').hide().filter(function(){
    return $(this).data('book-title') == bookValue;
  }).show();
});

Upvotes: 1

Related Questions