级联下拉不会填充MVC5

时间:2015-09-01 08:29:25

标签: c# jquery ajax asp.net-mvc

我对MVC很新,我正在尝试创建一个级联下拉菜单。用户将选择练习的名称,下面的下拉列表将填充在该练习中工作的配镜师的姓名。

配镜师型号:

public class Optician
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid OpticianId { get; set; }

[ForeignKey("User")]
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public IEnumerable<SelectListItem> UserList { get; set; }

[ForeignKey("Practice")]
public Guid PracticeId { get; set; }
public virtual Practice Practice { get; set; }
public IEnumerable<SelectListItem> PracticeList { get; set; }

public virtual ICollection<ApplicationUser> Users { get; set; }

public virtual ICollection<Practice> Practices { get; set; }
}

练习模型:

public class Practice
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "Practice")]
public Guid PracticeId { get; set; }

[Display(Name = "Practice Name")]
public string PracticeName { get; set; }


public virtual ICollection<Optician> Opticians { get; set; }

public virtual ICollection<Booking> Bookings { get; set; }
}

应用用户模型:

public class ApplicationUser : IdentityUser
{
[Display(Name = "Title")]
public string Title { get; set; }

[Display(Name = "First Name")]
public string FirstName { get; set; }

[Display(Name = "Last Name")]
public string LastName { get; set; }
}

控制器:

public ActionResult TestDropDown()
    {

        var practices = new SelectList(db.Practices, "PracticeId", "PracticeName");
        ViewData["Practices"] = practices;

        return View();
    }

    [HttpPost]
    public JsonResult Opticians(Guid? Id)
    {
        var opticianList = db.Opticans.Where(a => a.PracticeId == Id).Select(a => a.User).ToList();


        return Json(opticianList, JsonRequestBehavior.AllowGet);
    }

观点:

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script>
$(document).ready(function () {
    $("#Optician").prop("disabled", true);
    $("#Practice").change(function () {
        $.ajax({
            url : "@Url.Action("Opticians","Bookings1")",
            type : "POST",
            data : {Id : $(this).val() }
        }).done(function(OpticianList){
            $("#Optician").empty();
            for (var i = 0; i < OpticianList.length; i++) {
                $("#Optician").append("<option>" + OpticianList[i].FirstName + "</option>");
            }
            $("#Optician").prop("disabled", false);
        });
});
});

</script>


@using (Html.BeginForm("TestDropDown", "Bookings1", FormMethod.Post))
{
@Html.AntiForgeryToken()
<h4>Select Practcie & Opticians</h4>
<hr />
@Html.ValidationSummary()
<div class="form-group">
    @Html.Label("Select Practice :", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("PracticeId", ViewData["Practices"] as SelectList, new { @class = "form-control" })
    </div>
</div><br />
<div class="form-group">
    @Html.Label("Select Optician :", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        <select id="Optician"></select>
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Submit" />
    </div>
</div>
}

我可以选择练习的名称,但不会填充配镜师名字的下拉列表。 任何帮助将不胜感激 感谢

2 个答案:

答案 0 :(得分:1)

您首先<select>id="PracticeId",但您的脚本引用了id="Practice"的元素,该元素不存在,因此永远不会运行。将脚本更改为

var optician = $("#Optician"); // cache elements that you repeately refer to
optician.prop("disabled", true);
$("#PracticeId").change(function () { // change the selector
  $.ajax({
      url : "@Url.Action("Opticians","Bookings1")",
      type : "POST",
      data : {Id : $(this).val() }
  }).done(function(OpticianList){
      optician.empty();
      for (var i = 0; i < OpticianList.length; i++) {
          optician.append("<option>" + OpticianList[i].FirstName + "</option>");
      }
      optician.prop("disabled", false);
  });
});

或者您可以使用.getJSON()快捷方式

$.getJSON('@Url.Action("Opticians","Bookings1")', { Id : $(this).val() }, function(OpticianList) {
  // add the option elements
}

由于您只需要FirstName的{​​{1}}属性,因此您的控制器代码应为

ApplicationUser

并将脚本调整为

var opticianList = db.Opticans.Where(a => a.PracticeId == Id).Select(a => a.User.FirstName)

optician.append("<option>" + OpticianList[i] + "</option>");

所以你不要通过线路发送大量你从未使用过的额外数据。

答案 1 :(得分:0)

在您的行动中尝试此操作:

    [HttpPost]
    public JsonResult Opticians(Guid? Id)
    {
        var opticianList = db.Opticans.Where(a => a.PracticeId == Id).Select(a => a.User).ToList();
        SelectList mySelectList = new SelectList(opticianList, "IDField", "DisplayField", 0);

        return Json(mySelectList );
    }

以下是我实施本文时所遵循的帖子。 Fill drop down list on selection of another drop down list