MVC realizes the linkage effect of drop-down box (single choice)


For the linkage effect of the drop-down box, we take the Department position as an example. When selecting a department, it is associated with the position of the Department. The writing method of the drop-down box is not much, please refer to the previous article for details


Among them, Dept is the attribute of the Department, deptlist is the attribute of the Department drop-down box, job is the attribute of the position, joblist is the attribute of the position drop-down box. Please refer to the previous article for the binding of the drop-down box

@using (Html.BeginForm("aaai003sch", "aaa", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
     @Html.LabelFor(m => m.dept, new { @class = "col-sm-2 control-label" })
       @Html.DropDownListFor(model => model.dept, Model.deptlist, new { @class = "form-control select2 ", style = "width: 100%;" })
       @Html.ValidationMessageFor(m => m.dept, "", new { @class = "text-danger" })
    @ Html.LabelFor(m => m.job, new { @class = "col-sm-2 control-label" })
       @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" })

When departments change, positions change accordingly

//Get hotels by city
 $("#dept").change(function () {
  var url = rootUrl + "aaa/GetJobByDept";
   var dept = $(this).val(); // Get the value of the Department
   var job = $("#job");
   job.empty();  // Clear the value of the current position
   //This sentence is very important, because we use the select2 plug-in. If we don't use this plug-in, we can remove this sentence
   job.select2('val', '');
    cache: false,
    type: "GET",
    url: url,
    data: { "Dept": dept},
    success: function (data) {
     $.each(data, function (id, option) {

    error: function (xhr, ajaxOptions, thrownError) {
     Toastr ["error"] ("please select Department");

Run the URL in JS. This program is written in the controller

[description ("get position by department")]
  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)
   return Json(result, JsonRequestBehavior.AllowGet);

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.