欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

MVC实现下拉框联动的实例详解

程序员文章站 2022-03-19 22:56:34
...
这篇文章主要为大家详细介绍了MVC实现下拉框联动效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

下拉框联动效果,我们以部门--职位为例,选择部门时,关联到该部门的职位.下拉框的写法就不多说了,详细请参照前文.

视图:

其中,dept是部门的属性,deptlist是部门下拉框的属性,job是职位的属性,joblist是职位下拉框的属性,下拉框绑定请参照前文

@using (Html.BeginForm("aaai003sch", "aaa", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
 @Html.AntiForgeryToken()
 <p class="modal-body">
  <p class="form-horizontal">
    <p class="form-group">
     @Html.LabelFor(m => m.dept, new { @class = "col-sm-2 control-label" })
      <p 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" })
      </p>
    </p>
    <p class="form-group">
    @ Html.LabelFor(m => m.job, new { @class = "col-sm-2 control-label" })
      <p 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" })
      </p>
    </p>
  </p>
 </p>
</p>

当部门变动的时候,职位也相应改变:


//根据城市获取酒店
 $("#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实现下拉框联动的实例详解的详细内容,更多请关注其它相关文章!