简体   繁体   English

使用C尖锐对象动态填充选择

[英]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. 我已经看到了许多关于如何使用静态类型的列表的答案,但是没有看到来自asp.net对象的答案。

public class Book
{

    public string Title { get; set; }

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

}

Model.books is a list of Book objects above. Model.books是上面的Book对象的列表。

In cshtml: 在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: 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? 书或章节不多,因此仅通过所有书而不是使用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). 我主要不确定如何首先将我的Books列表添加到JQuery(我不习惯于Web开发)。

You can store the book title associated with chapter as data-* attribute for option element in chapters dropdown. 您可以将与章节关联的书名存储为章节下拉列表中选项元素的data-*属性。

@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: 然后使用“书”下拉列表中“选定书”元素的值来过滤与data属性匹配的章节以启用它们:

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

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

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