2017-04-04 3 views
-1

In meinem Projekt habe ich kaskadierte Dropdown-Liste mit jquery AJAX und es funktioniert, aber ich muss die zweite Dropdown-Liste auf Kontrollkästchen ändern, um die Stadt basierend auf den ausgewählten Bezirke auswählen aus der ersten Dropdown-Liste und auch die mit Checkbox ausgewählten Elemente müssen in der Datenbank gespeichert werden. Aber ich bin neu in MVC und ich bin nicht in der Lage, den Code für das Kontrollkästchen in der richtigen Weise zu geben.Änderung Dropdown-Liste zu Kontrollkästchen in AJAX JQuery in MV

Controller

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

Ansicht erstellen

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

Ich denke, diesen Teil, das ich in jquery ändern müssen, aber ich bin nicht in der Lage

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> 
zu tun

das ist mein Teil meines Codes. kann jemand bitte helfen Sie mir

Beispiel

<!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> 

Referenzen unten die Lösung

+0

Nicht klar, was Sie tun möchten.Möchten Sie für jede Stadt, die dem ausgewählten Bezirk zugeordnet ist, ein Kontrollkästchen erstellen, damit Sie mehrere Städte auswählen können? –

+0

ja, wenn ich Bezirk wählen möchte ich Städte als Checkbox – user256

Antwort

0

Wie immer starten, indem Sie Ansicht Modelle Erstellung Ihrer Mangel in der Ansicht zu vertreten, was

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

Ein d Erstellen Sie eine 10 für CityVM. In /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> 

und eine Teilansicht in Ihrem Ajax-Aufruf zurückgegeben werden - _FetchCities.cshtml

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

Und in der Hauptansicht

@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" /> 
} 

Ihr Code-Controller wird dann

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` 
    } 
} 

Und schließlich ist Ihr Skript

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

Was ist die Verwendung von Editor-Vorlage? – user256

+1

Es erzeugt das korrekte html für jedes 'CityVM' in der Sammlung (die Alternative besteht darin, eine' for' -Schleife in der Hauptansicht zu verwenden, aber die Verwendung einer 'EditorTemplate' macht es wiederverwendbar (und weniger Code) –

0

Ja, Sie für die zweite Drop-Bootstrap-Multi auswählen können zu finden:

<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> 

Modell:

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


     } 

Controller:

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

SnapShot: UI of View

Receiving data to action method

+0

was wird der Code in Controller MultiSelectController und cityDropDownList sehen, wie man Wert auf die Multidrop-Liste, bekomme ich nicht den Code richtig – user256

+0

Nichts ist nur eine Methode, die geben Städte als JSON. –

+0

aktualisiert .. Lösung –

Verwandte Themen