级联下拉不会填充

时间:2015-08-31 16:28:07

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

我是MVC5和JQuery的新手,我试图创建一个级联下拉菜单。当用户从下拉列表中选择练习时,我试图让在该练习中工作的配镜师进行填充。

配镜师型号:

 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 PracticeListItems = (from d in db.Practices
                                 select d.PracticeName).ToList();

        SelectList Practice = new SelectList(PracticeListItems);
        ViewData["Practice"] = Practice;

        return View();
    }

    public JsonResult Opticians(Guid? Id)
    {
        var OpticianList = (from d in db.Opticans
                            where d.PracticeId == Id
                            select d.User.FirstName).ToList();

        return Json(OpticianList);
    }

观点:

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

<script>
$(document).ready(function () {
    $("#Optician").prop("disabled", true);
    $("#Practice").change(function () {
        if ($("#Practice").val() != "Select") {
            var PracticeOptions = {};
            PracticeOptions.url = "/Bookings1/Opticians";
            PracticeOptions.type = "POST";
            PracticeOptions.data = JSON.stringify({ Practice: $("#Practice").val() });
            PracticeOptions.datatype = "json";
            PracticeOptions.contentType = "application/json";
            PracticeOptions.success = function (OpticianList) {
                $("#Optician").empty();
                for (var i = 0; i < OpticianList.length; i++) {
                    $("#Optician").append("<option>" + StatesList[i] + "</option>");
                }
                $("#Optician").prop("disabled", false);
            };
            PracticeOptions.error = function () { alert("Error in getting Practices"); };
            $.ajax(PracticeOptions);
        }
        else {
            $("#Optician").empty();
            $("#Optician").prop("disabled", true);
        }
    });
});

@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("Practice", 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>
}

但是,当我运行应用程序时,“实践名称”会填充,但“配镜师名字”不会填充。没有错误,我不确定我哪里出错了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

好像你的代码存在一些问题。从你的SelectList开始。

当您定义选择列表时,如果您告诉它您的值和文本属性是什么,它会有所帮助。

public ActionResult TestDropDown()
{
    var practices = new SelectList(db.Practices, "PracticeId", "PracticeName");
    ViewData["Practices"] = practices;
    return View();
}

然后你应该在你的Opticians json结果中返回更多信息

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

    return Json(opticianList);
}

在您的javascript中,一旦您获得了名称,您就可以引用结果的FirstName属性。

$(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);
        });
    });
});

我不确定你为什么要将参数Practice传递给参数Id的动作,但是应该在上面的代码中修复它。