2017-04-04 79 views
-1

在我的项目中,我使用级联下拉列表使用jQuery的ajax,它的工作原理,但我需要将第二个下拉列表更改为复选框来选择城市根据所选区从第一个下拉列表以及使用复选框选择的项目需要保存在数据库中。但我是MVC和Iam的新手,无法以正确的方式给出复选框的代码。将下拉列表更改为ajax中的复选框mvc

控制器

public ActionResult Create() 
    { 
     ViewBag.DistrictId = new SelectList(db.DistrictMasters, "Id", "DistrictName"); 

     return View(); 
    } 

public JsonResult GetPosts(string id) 
    { 
     List<SelectListItem> posts = new List<SelectListItem>(); 
     var postList = this.Getpost(Convert.ToInt32(id)); 
     var postData = postList.Select(m => new SelectListItem() 
     { 
      Text = m.PostName, 
      Value = m.Id.ToString(), 
     }); 
     return Json(postData, JsonRequestBehavior.AllowGet); 
    } 

public IList<PostMaster> Getpost(int DistrictId) 
    { 
     return db.PostMasters.Where(m => m.DistrictID == DistrictId).ToList(); 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Create([Bind(Include = "Id,PostId,DistrictId")] Agent agent, FormCollection formdata) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Agents.Add(agent); 
      await db.SaveChangesAsync(); 
      return RedirectToAction("Index"); 
     } 

     return View(agent); 
    } 

视图中创建

@model A.Models.Agent 

@using (Html.BeginForm()) 
{ 
@Html.AntiForgeryToken() 
<div class="form-horizontal"> 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
<div class="form-group"> 
     @Html.LabelFor(model => model.PostMaster.DistrictID, "DistrictName", htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownList("DistrictId", ViewBag.DistrictId as SelectList, "-- Please Select --", new { style = "width:250px" }) 
     </div> 
    </div> 

    <div class="form-group"> 
     @Html.LabelFor(model => model.PostId, "PostName", htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownList("PostMaster", new SelectList(string.Empty, "Value", "Text"), "-- Please select --", new { style = "width:250px", @class = "dropdown1" }) 
     </div> 
    </div> 
<div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Create" class="btn btn-default" /> 
     </div> 
    </div> 
</div> 
} 

<script type="text/javascript"> 
$(document).ready(function() { 
    //District Dropdown Selectedchange event 
    $("#DistrictId").change(function() { 
     $("#PostMaster").empty(); 
     $.ajax({ 
      type: 'POST', 
      url: '@Url.Action("GetPosts")', // Calling json method 
      dataType: 'json', 
      data: { id: $("#DistrictId").val() }, 
      // Get Selected post id. 
      success: function (posts) { 
       $.each(posts, function (i, post) { 
        $("#PostMaster").append('<option value="' + post.Value + '">' + 
         post.Text + '</option>'); 
       }); 
      }, 
      error: function (ex) { 
       alert('Failed to retrieve post.' + ex); 
      } 
     }); 
     return false; 
    }) 
}); 

我觉得这部分,我需要在jQuery的改变,但我不能够做到这一点

success: function (posts) { 
       $.each(posts, function (i, post) { 
        $("#PostMaster").append('<option value="' + post.Value + '">' + 
         post.Text + '</option>'); 
       }); 
      }, 


    <div class="form-group"> 
     @Html.LabelFor(model => model.PostId, "PostName", htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownList("PostMaster", new SelectList(string.Empty, "Value", "Text"), "-- Please select --", new { style = "width:250px", @class = "dropdown1" })  

     </div> 
    </div> 

这是我的我的代码的一部分。任何人都可以请帮我找到解决办法

+0

不清楚你想要做什么。您是否想要为与所选区域相关联的每个城市生成一个复选框,以便您可以选择多个城市? –

+0

是的,当我选择分区我想城市复选框 – user256

回答

0

与往常一样,通过创建视图模型来表示视图

public class AgentVM 
{ 
    .... 
    [Required(ErrorMessage = "Please select a District")] 
    [Display(Name = "District")] 
    public int? SelectedDistrict { get; set; } 
    public IEnumerable<SelectListItem> DistrictList { get; set; } 
    public IEnumerable<CityVM> Cities { get; set; } 
} 
public class CityVM 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public bool IsSelected { get; set; } 
} 

什么你想开始一个d为CityVM创建EditorTemplate。在/Views/Shared/EditorTemplates/CityVM.cshtml

@model CityVM 
<div> 
    @Html.HiddenFor(m => m.ID) 
    @Html.HiddenFor(m => m.Name) 
    <label> 
     @Html.CheckBoxFor(m => m.IsSelected) 
     <span>@Model.Name</span> 
    </label> 
</div> 

和局部视图来在你的Ajax调用返回 - _FetchCities.cshtml

@model AgentVM 
@Html.EditorFor(m => m.Cities) 

,并在主视图

@model AgentVM 
@using (Html.BeginForm()) 
{ 
    .... 
    @Html.LabelFor(m => m.SelectedDistrict) 
    @Html.DropDownListFor(m => m.SelectedDistrict, Model.DistrictList, "Please select") 
    @Html.ValidationMessageFor(m => m.SelectedDistrict) 
    .... 
    <div id="cites"> 
     @Html.EditorFor(m =>m.Cities) 
    </div> 
    <input type="submit" value="Create" /> 
} 

控制器代码届时将

public ActionResult Create() 
{ 
    AgentVM model = new AgentVM(); 
    ConfigureViewModel(model); 
    return View(model); 
} 
[HttpPost] 
public ActionResult Create(AgentVM model) 
{ 
    if (!ModelState.IsValid) 
    { 
     ConfigureViewModel(model); 
     return View(model); 
    } 
    // Get the ID's of the selected cities 
    IEnumerable<int> selectedCities = model.Cities.Where(x => x.IsSelected).Select(x => x.ID); 
    // Initialize you data model 
    // Map its values from the view model 
    // Save and redirect 
} 
public PartialViewResult FetchCities(int id) 
{ 
    // Adjust property names as required 
    IEnumerable<CityVM> cities = db.Cities.Where(x => x.DistrictID == id).Select(x => new CityVM 
    { 
     ID = x.CityID, 
     Name = x.CityName 
    }); 
    AgentVM model = new AgentVM() 
    { 
     Cities = cities 
    }; 
    return PartialView("_FetchCities", model); 

} 
private ConfigureViewModel(AgentVM model) 
{ 
    model.DistrictList = new SelectList(db.DistrictMasters, "Id", "DistrictName"); 
    // The following would only be applicable to a view where you editing existing values 
    if (model.Cities == null && model.SelectedDistrict.HasValue) 
    { 
     // Get cities based on SelectedDistrict and map to a collection of `CityVM` 
    } 
} 

最后你的脚本将是

var url = '@Url.Action("FetchCities")'; 
var cities = $('#cities'); 
$('#SelectedDistrict').change(function() { 
    var selectedCity = $(this).val(); 
    if (!selectedCity) { 
     cities.empty(); 
     return; 
    } 
    $.get(url, { id: selectedCity }, function(data) { 
     cities.html(data); 
    } 
}) 
+0

编辑器模板的用途是什么? – user256

+1

它为集合中的每个'CityVM'生成正确的html(替代方法是在主视图中使用'for'循环,但使用'EditorTemplate'使其可重用(并且代码更少) –

0

是的,你可以使用引导多选择第二个下拉

<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Index</title> 
</head> 
<body> 
    <h4> Cascading dropdown with checkbux - Multiselect</h4> 
    <div class="container"> 
     <div class="col-lg-6"> 
      @Html.DropDownList("Country", (IEnumerable<SelectListItem>)ViewBag.Locations, "Select from", new { @class = "form-control" }) 
     </div> 
     <div class="col-lg-6"> 
      @Html.DropDownList("City", new SelectList(Enumerable.Empty<SelectListItem>()), new { @class = "multiselect", @multiple = "multiple" }) 
     </div> 
     <br> 
     <br> 
     <br> 
     <br> 
     <div> 
      <input type="button" id="btnSubmit" value="Submit" class="btn-success" /> 
     </div> 
    </div> 
</body> 
</html> 

参考文献:

<link href="~/Content/bootstrap.css" rel="stylesheet" /> 
<link href="~/Content/bootstrap-multiselect.min.css" rel="stylesheet" /> 

<script src="~/Scripts/jquery-1.10.2.js"></script> 
<script src="~/Scripts/bootstrap.min.js"></script> 
<script src="~/Scripts/bootstrap-multiselect.min.js"></script> 

    <script> 

    $(document).ready(function() { 
     //once the page load , it load drop down with city - #City 
     var CityDropdown = ""; 
     $.ajax({ 
      url: '/MultiSelectController/cityDropDownList', 
      type: "GET", 
      async: true, 
      success: function (result, textStatus, jqXHR) { 
      // console.log("result"); 
      // console.log(result); 
       $.each(result, function (i, data) { 
        CityDropdown += "<option " + " value=" + data.CityId + ">" + data.CityName + "</option>"; 
       }); 
       $('#City').append(CityDropdown); 
       $('#City').multiselect('rebuild'); 
      }, 
      error: function (XMLHttpRequest, textStatus, errorThrown) { 
       alert("Error"); 
      } 
     }); 

     $('#Country').change(function() { 
      // alert('im change country') 
      $.ajax({ 
       url: '/MultiSelectController/cityDropDownListselected', 
       type: "GET", 
       async: false, 
       success: function (result, textStatus, jqXHR) { 
        // console.log("result"); 
        // console.log(result); 
        var makeCityObj = []; 
        $.each(result, function (i, data) { 
         makeCityObj.push(data.CityId); 
        }); 
        $('#City').val(makeCityObj); 
        $("#City").multiselect("refresh"); 
        $("#City").multiselect("rebuild"); 
       } 
      }); 

     }); 

     $('#btnSubmit').click(function() { 
      // alert("Hi , i'm submit btn ") 
      var getSelectCity = $('#City').val(); 

     // console.log("getSelectCity"); 
     // console.log(getSelectCity); 

      //make the child object 
      var cityObj = $('#City').val(); 
      var CityArray = []; 
      if (cityObj != null) 
      { 
       $.each(cityObj, function (i, data) { 
        var obj = { 
         CityId: parseInt(data), 
        } 
        CityArray.push(obj); 
       }); 
      } 

      var sendObj = { 
       CountryId : parseInt($('#Country').val()), 
       SelectedCity : CityArray, 
      } 

     // before send the data to server let check in browser dev tool , cosole.log 
      console.log("sendObj"); 
      console.log(sendObj); 

      $.ajax({ 
       type: 'POST', 
       url: '/MultiSelectController/Submit', 
       contentType: 'application/json', // data, that we are going to send to server 
       // dataType: "text", // retrun type of data 
       // async: false, // by default asyn is true 
       traditional: true, 
       data: JSON.stringify(sendObj), 
       success: function (data, textStatus, jqXHR) { 
        alert('susccess'); 
       }, 
       error: function (XMLHttpRequest, textStatus, errorThrown) { 
        alert("Error"); 
       } 
      }); 

     }); 


     //intialize the multiselection 

     $('.multiselect').multiselect({ 
      enableFiltering: true, 
      enableHTML: true, 
      buttonClass: 'btn btn-white btn-default btn-sm', 
      templates: { 
       button: '<button type="button" class="multiselect dropdown-toggle col-sm-12 col-xs-12" data-toggle="dropdown"><span class="multiselect-selected-text"></span> &nbsp;<b class="fa fa-caret-down"></b></button>', 
       ul: '<ul class="multiselect-container dropdown-menu"></ul>', 
       filter: '<li class="multiselect-item filter"><div class="input-group input-group-sm"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>', 
       filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>', 
       li: '<li><a tabindex="0"><label class="label-sm"></label></a></li>', 
       divider: '<li class="multiselect-item divider"></li>', 
       liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>' 
      }, 
      maxHeight: 200, 
      numberDisplayed: 2, 
      includeSelectAllOption: true, 
     }); 
     $("select.multiselect") 
       .each(function (i, el) { 
        $(el).parent().find(".multiselect-container>li>a.multiselect-all label").removeClass("label-sm") 
       }) 
     $("select.multiselect").parent().find('.btn-group').addClass("col-sm-12 col-xs-12 no-padding-left no-padding-right"); 

    }) 



</script> 

型号:

 public class SubmitViewModel { 

      public int CountryId { get; set; } 
      public string CountryName { get; set; } 
      public List<BPCity> SelectedCity { get; set; } 

     } 
     public class BPCity 
     { 

      public int CityId { get; set; } 
      public string CityName { get; set; } 




     } 
     public class BPCountry 
     { 
      public int CountryId { get; set; } 

      public string CountryName { get; set; } 


     } 

控制器:

 public class MultiSelectControllerController : Controller 
    { 
     // GET: MultiSelectController 
     public ActionResult Index() 
     { 

      //Assigning generic list to ViewBag 

      var getCountryList = countryDropDownList(); 

      List<SelectListItem> ObjList = new List<SelectListItem>(); 
      foreach (var item in getCountryList) 
      { 
       ObjList.Add(new SelectListItem 
       { 
        Value = "" + item.CountryId, 
        Text = item.CountryName, 
       }); 
      } 

      ViewBag.Locations = ObjList; 

      return View(); 
     } 
     public List<BPCountry> countryDropDownList() 
     { 
      List<BPCountry> _ob = new List<BPCountry>(); 
      for (int x = 1; x < 40; x++) 
      { 
       BPCountry _cb = new BPCountry 
       { 

        CountryId = x, 
        CountryName = "country" + "-" +x, 
       }; 
       _ob.Add(_cb); 
      } 

      return _ob; 
     } 


     public ActionResult Submit(SubmitViewModel sendObj) { 

      return Json("" ,JsonRequestBehavior.AllowGet); 
     } 

     public ActionResult cityDropDownListselected() 
     { 
      List<BPCity> _ob = new List<BPCity>(); 
      for (int x = 1; x < 4; x++) 
      { 
       BPCity _cb = new BPCity 
       { 

        CityId = x, 
        CityName = "cxcvity" + x, 
       }; 
       _ob.Add(_cb); 
      } 

      return Json(_ob, JsonRequestBehavior.AllowGet); 
     } 


     public ActionResult cityDropDownList() 
     { 
      List<BPCity> _ob = new List<BPCity>(); 
      for (int x = 1; x < 10; x++) 
      { 
       BPCity _cb = new BPCity 
       { 

        CityId = x, 
        CityName = "cxcvity" + x, 
       }; 
       _ob.Add(_cb); 
      } 

      return Json(_ob , JsonRequestBehavior.AllowGet); 
     } 

快照: UI of View

​​

+0

控制器MultiSelectController和cityDropDownList视图中的代码是什么,如何获得多点下拉列表的值,我没有正确获取代码 – user256

+0

没有它只是一个方法,让城市成为json。 –

+0

更新..解决方案 –