ASP.NET MVC DropDownList的使用

一、控制器·

 
 public ActionResult Index()
        {
            if (ViewBag.courseID != null)
            {
            }
            else
            {
                ViewBag.studentID = new SelectList(db.Students,"ID","LastName");
                ViewBag.courseID = new SelectList(db.Courses, "CourseID", "Title");
            }
            return View();
        }

二、Ajax

(1)服务器

        public ActionResult DDL(int studentID)
        {
            //string a = studentID;
            //var courseID = db.Enrollments.Where(s => s.StudentID == studentID).Select(s=>s.CourseID);
            //foreach (var cid in courseID)
            //{
            //    var course = db.Courses.Where(s => s.CourseID == cid);
            //    IEnumerable<>
            //}
            //var q = from a in db.Enrollments
            //        join b in db.Students on a.StudentID equals studentID
            //        join c in db.Courses on a.CourseID equals c.CourseID
            //        group new {
            //           c=c
            //        } by c.CourseID into  g
            //        select new
            //        {

            //            CourseID = g.Key,
            //            Title = g.FirstOrDefault,
            //        };

            var q = from a in db.Enrollments
                    from b in db.Students
                    from c in db.Courses
                    where a.StudentID == studentID && a.CourseID == c.CourseID
                    select new
                    {

                        CourseID = c.CourseID,
                        Title = c.Title
                    };
            var result=q.Distinct().ToList();//去重Distinct()

            //return RedirectToAction("Index");
            return Json(q.Distinct().ToList());
        }
(2)前端
    @using (Html.BeginForm("DDL", "Home"))
    {
    @Html.Label("课程:")
        @*@Html.DropDownList("courseID")*@
    @Html.DropDownList("studentID")
    @Html.DropDownList("courseID",ViewBag.Course as IEnumerable<SelectListItem>, "请选择课程")
        <input type="submit"value="提交" />
    }
  <script type="text/javascript">
        //$(function () {
        //    $("#courseID").change(function () {
        //        alert(this.id)
        //    })
        //})
       
        //$(function () {
        //    $("#courseID").change(function () {
        //        alert($("#courseID").val())
        //        //alert(this.val())
        //    })
        //})


        //var value=$("#courseID").val();
        //alert(value);


        $(function () {
            $("#studentID").change(function () {
                $.ajax({
                    url: "@Url.Action("DDL","Home")" + "?studentID= " + $(this).val(),
                    type: 'POST',
                    data: null,
                    dataType: "json",
                    success: function (data) {
                        $("#courseID").empty();
                      //  $("#courseID").append("<option value=0>Ajax</option>")
                        var json = eval(data); //数组
                        $.each(json, function (index, item) {
                            //循环获取数据    
                            var CourseID = json[index].CourseID;
                            var Title = json[index].Title;
                            //  $("#list").html($("#list").html() + "<br>" + name + " - " + idnumber + " - " + sex + "<br/>");
                            $("<option value='" + CourseID + "'>" + Title + "</option>").appendTo("#courseID");
                        });
                    }
                });
            });
        });


    </script>
    @Html.DropDownList("studentID"),studentID即为ViewBag.studentID,studentID也是下拉框的id,下拉框的Value和Text会自动填充。

    @Html.DropDownList("courseID",ViewBag.Course as IEnumerable<SelectListItem>, "请选择课程"),第一个参数是下拉框的id,第二个即ViewBag.Course,第三个参数为下拉框Text默认值。

Linq To SQL三张表联结查询,Distinct()去重。

JQuery Ajax语法,使用Ajax实现DropDownList两级联动,在ASP.NET MVC中Ajax最好使用POST方式,否则会报500的错误码。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET MVC中的下拉列表联动是一种常见的需求,它可以实现当一个下拉列表的选项发生改变时,另一个下拉列表的选项也随之改变。下面是我用300字回答的步骤: 1. 首先,创建两个Model来表示这两个下拉列表的选项。例如,一个是CountryModel,另一个是CityModel。这两个Model都需要包含相应的属性,如CountryId和CountryName,CityId和CityName。 2. 在Controller中,创建两个Action来获取这两个下拉列表的选项。例如,一个是GetCountryList,另一个是GetCityList。这两个Action应该返回相应的选项数据,例如通过调用数据库获取国家和城市的数据,并将其转换为对应的Model列表。 3. 在View中,使用HTMLHelper的DropDownListFor方法创建两个下拉列表。第一个下拉列表使用CountryId作为选中值,并指定一个名为CountryList的ViewBag变量作为选项列表。第二个下拉列表使用CityId作为选中值,并指定一个名为CityList的ViewBag变量作为选项列表。例如: @Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.CountryList, "-请选择国家-") @Html.DropDownListFor(model => model.CityId, (IEnumerable<SelectListItem>)ViewBag.CityList, "-请选择城市-") 4. 使用jQuery监听第一个下拉列表的change事件,当选中值发生改变时,触发一个Ajax请求。例如: $("#CountryId").change(function() { var selectedCountryId = $(this).val(); $.ajax({ url: '/Controller/GetCityList', type: 'GET', data: { countryId: selectedCountryId }, success: function(response) { $("#CityId").html(response); } }); }); 5. 在Controller的GetCityList Action中,根据传入的countryId参数获取对应的城市数据,并将其转换为一个包含相应选项的字符串,然后将其返回给前端。例如: public ActionResult GetCityList(int countryId) { // 根据countryId获取对应的城市列表数据 var cityData = // 数据库操作或其他方式获取城市数据; // 将城市列表数据转换为一个包含选项的字符串 var cityOptions = ""; foreach (var city in cityData) { cityOptions += "<option value='" + city.CityId + "'>" + city.CityName + "</option>"; } return Content(cityOptions); } 通过以上步骤,就可以实现ASP.NET MVC中的下拉列表联动效果。当第一个下拉列表的选项发生改变时,第二个下拉列表的选项会根据选择的值进行更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值