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

时间:2015-10-20 22:12:30

标签: javascript jquery asp.net-mvc html-select form-submit

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

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

以下是我使用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; }
}

1 个答案:

答案 0 :(得分:2)

使用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以获取类似示例