编程语言
首页 > 编程语言> > javascript – 如何在表单提交后保留级联下拉列表选定的项目?

javascript – 如何在表单提交后保留级联下拉列表选定的项目?

作者:互联网

当页面加载一切正常.但是当我提交表单时,我的下拉列表在页面刷新后丢失了之前选择的项目.

如何修改我的函数以初始化下拉列表并保留之前选定的项目(两者都存在).

这是我用javascript初始化我的下拉列表的视图:

@model Models.Book

@{
    ViewBag.Title = "Index";
}

@section scripts {
<script type="text/javascript">
    $(function() {
        $.getJSON("/Home/Books/List", function(data) {
            var items = "<option>--------------------</option>";
            $.each(data, function(i, book) {
                items += "<option value='" + book.Value + "'>" + book.Text + "</option>";
            });
            $("#Books").html(items);
        });

        $("#Books").change(function() {
            $.getJSON("/Home/Chapters/List/" + $("#Books> option:selected").attr("value"), function(data) {
                var items = "<option>--------------------</option>";
                $.each(data, function(i, chapter) {
                    items += "<option value='" + chapter.Value + "'>" + chapter.Text + "</option>";
                });
                $("#Chapters").html(items);                         
            });
        });             
    });               
</script>
}

@using (@Html.BeginForm("ListChapterContent", "Home"))
{
<div id="header">
    <label for="Books">Books</label>
    <select id="Books" name="Books"></select>

    <label for="Chapters">Chapters</label>
    <select id="Chapters" name="Chapters" onchange="this.form.submit();"></select>        
</div>

这是我的模型:

public class Book
{
    public string Translator{ get; set; }
    public string Edition{ get; set; }
    public List<Book> Books{ get; set; }
    public int SelectedBook { get; set; }
    public int SelectedChapter { get; set; }
}

解决方法:

使用HtmlHelpers生成控件而不是手动创建html,以便获得双向模型绑定.如果您使用视图模型,您会发现这是最简单的

public class BookVM
{
  [Required]
  public int? SelectedBook { get; set; }
  [Required]
  public int? SelectedChapter { get; set; }
  public SelectList BookList { get; set; }
  public SelectList ChapterList { get; set; }
}

调节器

public ActionResult Create()
{
  BookVM model = new BookVM();
  ConfigureViewModel(model);
  return View(model);
}

private void ConfigureViewModel(BookVM model)
{
  IEnumerable<Book> books = db.Books;
  model.BookList = new SelectList(books, "ID", "Name");
  if (model.SelectedBook.HasValue)
  {
    IEnumerable<Chapter> chapters= db.Books.Where(c => c.BookId == model.SelectedBook.Value);
    model.ChapterList = new SelectList(chapters, "ID", "Name");
  }
  else
  {
    model.ChapterList = new SelectList(Enumerable.Empty<SelectListItem>());
  }
}

并在视图中

@model BookVM
@using (@Html.BeginForm())
{
  @Html.LabelFor(m => m.SelectedBook)
  @Html.DropDownListFor(m => m.SelectedBook, Model.BookList, "-Please select-")
  @Html.ValidationMessageFor(m => m.SelectedBook)

  @Html.LabelFor(m => m.SelectedChapter)
  @Html.DropDownListFor(m => m.SelectedChapter, Model.ChapterList)
  @Html.ValidationMessageFor(m => m.SelectedChapter)
}

然后你的脚本变成(删除第一个)

var url = '@Url.Action("FetchChapters")'; // don't hard code url's
var chapters = $('#SelectedChapter');
$('#SelectedBook').change(function() {
  if (!$(this).val()) {
    return;
  }
  $.getJSON(url, { id:  $(this).val() }, function(data) {
    chapters.empty().append($('<option></option>').val('').text('-Please select-'));
    $.each(data, function(index, chapter) {
      subLocalities.append($('<option></option>').val(item.Value).text(item.Text));            
    });
  });
}); 

而你返回json的方法就是

public JsonResult FetchSubLocalities(int ID)
{
  var chapters= db.Books.Where(c => c.BookId == ID).Select(c => new
  {
    Value = c.ID,
    Name = c.Name
  });
  return Json(chapters, JsonRequestBehavior.AllowGet);
}

最后在POST方法中,如果需要返回视图

[HttpPost]
public ActionResult Create(BookVM model)
{
  if(!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model);
  }
  ....

有关类似示例,请参阅此DotNetFiddle

标签:javascript,jquery,asp-net-mvc,html-select,form-submit
来源: https://codeday.me/bug/20190918/1810351.html