使用MVC框架怎么实现一个下拉框联动效果?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
@using (Html.BeginForm("aaai003sch", "aaa", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <div class="modal-body"> <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(m => m.dept, new { @class = "col-sm-2 control-label" }) <div class="col-sm-10"> @Html.DropDownListFor(model => model.dept, Model.deptlist, new { @class = "form-control select2 ", style = "width: 100%;" }) @Html.ValidationMessageFor(m => m.dept, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @ Html.LabelFor(m => m.job, new { @class = "col-sm-2 control-label" }) <div class="col-sm-10"> @Html.DropDownListFor(model => model.job, Model.joblist, new { @class = "form-control select2 page-select2-area", style = "width: 100%;" }) @Html.ValidationMessageFor(m => m.job, "", new { @class = "text-danger" }) </div> </div> </div> </div> </div>
当部门变动的时候,职位也相应改变:
//根据城市获取酒店 $("#dept").change(function () { var url = rootUrl + "aaa/GetJobByDept"; var dept = $(this).val(); //获取部门的值 var job = $("#job"); job.empty(); //清空当前职位的值 //这句很重要,因我们用的是select2插件,若没有用这个插件可以去掉这句 job.select2('val', ''); $.ajax({ cache: false, type: "GET", url: url, data: { "Dept": dept}, success: function (data) { $.each(data, function (id, option) { job.append($('<option></option>').val(option.Id).html(option.Name)); }); job.trigger('change'); }, error: function (xhr, ajaxOptions, thrownError) { toastr["error"]("请选择部门"); } }); });
执行js里的URL,这个程式写在控制器里:
[Description("根据部门获取职位")] [AcceptVerbs(HttpVerbs.Get)] [LoginAllowView] public ActionResult GetJobByDept(string dept) { if (String.IsNullOrEmpty(dept)) { throw new ArgumentNullException("dept"); } StringBuilder sb = new StringBuilder(); sb = new StringBuilder(); sb.Append(" SELECT jobid,jobname "); sb.Append(" FROM job_file "); sb.Append(" LEFT JOIN dept_file ON jobdept = deptid "); sb.AppendFormat(" WHERE deptid='{0}'", dept); DataTable dt = sqlHelper.getData(sb.ToString()); var result = dt.AsEnumerable().Select(row => new Item { Name = Utils.ObjToStr(row["jobname"]), Id = Utils.ObjToInt(row["jobid"], 0) }).ToList(); return Json(result, JsonRequestBehavior.AllowGet); }
看完上述内容,你们掌握使用MVC框架怎么实现一个下拉框联动效果的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。