如何在表单提交后保留级联下拉列表选定的项目? [英] How to keep cascade dropdownlist selected items after form submit?

查看:172
本文介绍了如何在表单提交后保留级联下拉列表选定的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When the page loads everything works fine. But when I submit the form my dropdownlists are loosing the previous selected items after page refresh.

如何修改我的函数以初始化下拉列表并保留以前选择的项目( (如果它们存在的话)。

How can I modify my function to initialize the dropdownlists and keep the previous selected items (on both) if they exist.

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

Here is my view with the javascript that initializes my dropdownlists:

@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,所以你得到2路模型绑定。如果你使用视图模型,你会发现这是最简单的

Use the HtmlHelpers to generate your controls rather than manually creating your html so you get 2 way model binding. You will find this easiest if you use a view model

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)
}

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

Then you script becomes (delete the first one)

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的方法是

and you method to return the json would be

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方法中,如果你需要返回视图

and finally in the POST method, if you need to return the view

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

另请参阅 DotNetFiddle 的类似例子

这篇关于如何在表单提交后保留级联下拉列表选定的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆