【问题标题】:Cascaded dropdown is throwing away the "Please Select"级联下拉菜单正在丢弃“请选择”
【发布时间】:2014-10-28 22:07:09
【问题描述】:

我终于让一对级联下拉菜单正常工作了。不幸的是,在第一个项目中选择一个项目后,第二个项目加载并立即丢弃空值“请选择”。我已经找到了如何使用 Text="Please Select", Value="0" 插入 SelectListItem,但我犹豫不决。如果可能的话,我想使用内置的空值。

我已经在一个自动生成的控制器和视图集中得到了所有这些,并且目前正在创建页面上。

控制器:

// GET: Books/Create
    public ActionResult Create()
    {
        ViewBag.AuthorID = new SelectList(db.Authors, "AuthorID", "AuthorName");
        //ViewBag.SeriesID = new SelectList(db.Series, "SeriesID", "SeriesName");
        ViewBag.SeriesID = new SelectList(db.Series.Where(v => v.SeriesID == 0), "SeriesID", "SeriesName");
        return View();
    }

    // POST: Books/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "BookID,BookName,AuthorID,SeriesID")] Book book)
    {
        if (ModelState.IsValid)
        {
            db.Books.Add(book);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.AuthorID = new SelectList(db.Authors, "AuthorID", "AuthorName", book.AuthorID);
        ViewBag.SeriesID = new SelectList(db.Series, "SeriesID", "SeriesName", book.SeriesID);
        return View(book);
    }

    public JsonResult GetSeries(int id)
    {
        SelectList list = new SelectList(db.Series.Where(v => v.AuthorID == id), "SeriesID", "SeriesName");

        return Json(new SelectList(db.Series.Where(v => v.AuthorID == id), "SeriesID", "SeriesName"));
    }

查看:

    <script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#AuthorID").change(function () {
            $("#SeriesID").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetSeries")', // calling json method
                dataType: 'json',
                data: { id: $("#AuthorID").val() },
                success: function (series) {
                    // contains the JSON formatted list passed from the controller
                    $.each(series, function (i, ser) {
                        $("#SeriesID").append('<option value="' + ser.Value + '">' + ser.Text + '</option>');
                    }); // adding option
                },
                error: function (ex) {
                    alert('Failed to retrieve series.' + ex);
                }
            });
            return false;
        })
    });
    </script>
    @using (Html.BeginForm())
    {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Book</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.BookName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BookName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BookName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AuthorID, "Author", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("AuthorID", null, "Please Select", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.AuthorID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.SeriesID, "Series", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("SeriesID", null, "Please Select", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.SeriesID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
    }

无论如何,我也尝试通过以下方式找出级联下拉菜单,但从未成功。我想也许通过遵循“公共 ActionResult Create()”方法中使用的格式,我可能会绕过空值的丢失。

我也想过尝试穿越两者;通过 Json 调用控制器方法并通过 ViewBag 加载,但我对这些方法的理解显然还不够先进,无法实现(如果可能的话)。

失败控制器:

[HttpPost]
[ActionName("GetSeries")]
public ActionResult GetSeries(int id)
{
    ViewBag.SeriesID = new SelectList(db.Series.Where(v => v.AuthorID == id), "SeriesID", "SeriesName");
    return View();
}

失败视图:

@using (Html.BeginForm("GetSeries", "Books", FormMethod.Post, new { id = "0" })) 
{
    <div class="form-group">
        @Html.LabelFor(model => model.AuthorID, "Author", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("AuthorID", null, "Please Select",
              htmlAttributes: new
              {
                  @class = "form-control",
                  onchange = "$('#AuthorID').submit()", 
                  name = "action:GetSeries" })
            @Html.ValidationMessageFor(model => model.AuthorID, "", new { @class = "text-danger" })
        </div>
    </div>
}

@using (Html.BeginForm()
{
     // All the other stuff from the view here.
}

【问题讨论】:

    标签: c# asp.net-mvc cascadingdropdown


    【解决方案1】:

    您需要在 ajax 函数中创建它(调用 empty 会清除 所有 选项,因此您需要将其添加回来)。另请注意,没有 内置空值!当您使用接受 optionLabel 的重载并使用 ajax 重新填充下拉列表时,html 助手添加的“请选择”选项,而不是 html 助手。

    $("#AuthorID").change(function () {
      $("#SeriesID").empty().append($('<option></option>').text('Please select'));
      ...
    

    注意,您不需要在 GetSeries() 方法中创建选择列表(它只是不必要的开销)

    public JsonResult GetSeries(int id)
    {
      var data = db.Series.Where(v => v.AuthorID == id).Select(s => new
      {
        Value = s.SeriesID,
        Text = s.SeriesName
      }
        return Json(data));
    }
    

    【讨论】:

    • 感谢您纠正我的措辞;不太确定该怎么称呼它。所以 append() 工作得很好。但我的数据现在显示为“未定义”。 empty() 是否擦除了我需要重新添加的其他内容?此外,empty() 是否会抛出除 ID 之外的所有内容?
    • 不是控制器代码的问题。它没有返回有效数据(我已经更新了它 - 使用冒号而不是逗号 - 啊)。如果它不起作用,请使用您的初始代码检查它是否有效。如果可行,则调试我上面提供的代码,看看是否还有其他错误
    • 我已经在 return 语句中注意到了这一点以及额外的 ) 。没修好,我用我原来的密码试了一下——没有骰子。
    • 哈,找到了!在视图的 javascript 中,我有“series.Text”,它需要是“ser.Text”。非常感谢!
    猜你喜欢
    • 2013-09-14
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多