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

MVC实现下拉框联动效果(单选)

程序员文章站 2023-10-30 14:48:22
下拉框联动效果,我们以部门--职位为例,选择部门时,关联到该部门的职位.下拉框的写法就不多说了,详细请参照前文. 视图: 其中,dept是部门的属性,deptlist是...

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

视图:

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

@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);
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。