且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC中的从属下拉列表

更新时间:2023-02-01 09:13:54

我需要一些AJAX调用吗?还是POST方法?那么,让我们这样做吧:

Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:

给您的DropdownLists一些ID可能是

Give your DropdownLists some id's probably:

 @Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", @class = "form-control" })
 @Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", @class = "form-control" })

在其中创建一个jsonResult函数,GetMembers和一些Magic:

Create a jsonResult function, GetMembers and some Magic right there:

<script type="text/javascript">

        $(document).ready(function () {
            //Dropdownlist Selectedchange event
            $("#ddshowTeams").change(function () {
                console.log("pehla andar");
                $("#ddshowMembers").empty();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetMembers")',
                    dataType: 'json',
                    data: { id: $("#ddshowTeams").val() },
                    success: function (mems) {
                        console.log("wich ayaeee");
                        // states contains the JSON formatted list
                        // of states passed from the controller
                        $.each(mems, function (i, member) {
                            $("#ddshowMembers").append('<option value="'
    + member.Value + '">'
    + member.Text + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert('Failed to retrieve states.' + ex);
                    }
                });
                return false;
            })
        });
</script>

并在您的控制器中:

 public JsonResult GetMembers(int id)
        {
            return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
        }