Populate DropDownList using AJAX MVC 4

前端 未结 3 1591
星月不相逢
星月不相逢 2020-12-09 04:34

I have a view in place that contains 2 @DropDownListFor\'s Helpers:

    @using (Html.BeginForm(\"CreateOneWayTrip\", \"Trips\"))
    {
        @Html.Validati         


        
相关标签:
3条回答
  • 2020-12-09 05:04

    The reason you are getting a colletion of strings "System.Web.Mvc.SelectListItemSystem" is that var lstCities = new SelectList(new[] { "City1", "City2", "City3" }); returns IEnumerable<SelectListItem> and String.Join("", lstCities) calls the .ToString() method of each SelectListItem item in the collection which returns "System.Web.Mvc.SelectListItemSystem" (not the value of the Text property of SelectListItem)

    The best way to populate the second dropdown list is to return json containing the collection of cities and update the DOM in the ajax success callback. There is no reason to create a SelectList - its just unnecessary extra overhead and you returning at least 3 times as much data back to the client as is necessary (the client has no concept of a C# SelectListItem class.

    public JsonResult FetchCities(int provinceId) // its a GET, not a POST
    {
        // In reality you will do a database query based on the value of provinceId, but based on the code you have shown
        var cities = new List<string>() { "City1", "City2", "City3" });
        return Json(cities, JsonRequestBehavior.AllowGet);
    }
    

    Then in the script (not sure why you have modified the default id from id="StartPointProvince" to id="province_dll", but)

    var url = '@Url.Action("FetchCities", "Trips")'; // Don't hard code your url's!
    var cities = $('#city_dll'); // cache it
    $("#province_dll").change(function () {
        var id = $(this).val(); // Use $(this) so you don't traverse the DOM again
        $.getJSON(url, { provinceId: id }, function(response) {
            cities.empty(); // remove any existing options
            $.each(response, function(index, item) {
                cities.append($('<option></option>').text(item));
            });
        });
    });
    

    Edit

    Further to OP's comments, if the database contained a table name Cities with fields ID and Name, then the controller method would be something like

    public JsonResult FetchCities(int provinceId) // its a GET, not a POST
    {
        var cities = db.Cities.Select(c => new
        {
          ID = c.ID,
          Text = c.Text
        }
        return Json(cities, JsonRequestBehavior.AllowGet);
    }
    

    and the script to create the options would be

    $.each(response, function(index, item) { // item is now an object containing properties ID and Text
        cities.append($('<option></option>').text(item.Text).val(item.ID));
    });
    
    0 讨论(0)
  • 2020-12-09 05:19

    Let's make it more simple

    • Step 1: Server side function / data

      public JsonResult FetchP(string O)
      {
          List<SelectListItem> PList = new List<SelectListItem>();
           PList = _PService.GetAllPActive()
                    .Select(i => new SelectListItem()
                               {
                                   Text = i.PName,
                                   Value = i.PID                                   
                               }).ToList();
      
          return Json(PList, JsonRequestBehavior.AllowGet);
      }
      
    • Step 2 : Client side function / data interpreter

      function FetchP()
      {
          var url = '@Url.Action("FetchP", "Your_Controller")'; 
          var PDD= $("#PDD");
          var ODD= $("#ODD").val(); 
      
          $.getJSON(url, { O: ODD}, function (response) {
              PDD.empty(); 
              debugger;
              $.each(response, function (index, item) {
                  debugger;
                  var p = new Option(item.Text, item.Value);
                  PDD.append(p);
              });
          });
      }
      
    • Step 3 : Call - client side function / start

    • List 1 :

      @Html.DropDownList("ODD", ViewBag.OList as IEnumerable<SelectListItem>, new { @id = "ODD", @class = "form-control", @onchange= "FetchP()" })
      
    • List 2 :

      @Html.DropDownList("PDD", ViewBag.PList as IEnumerable<SelectListItem>,new { @id = "PDD", @class = "form-control"})
      
    0 讨论(0)
  • 2020-12-09 05:27

    Can you try the following?

    This is a post that i answared some days ago. Font:Dynamic DropDownLists In MVC 4 Form

    You should create a ajax call in the change event of the province ddl. This call will request to an action and return the cities of selected province.

    $("province_dll").change(function(){
        $.ajax({
             url: 'getCitiesController/getCitiesAction',
             type: 'post',
             data: {
                   provinceId: provinceIdVar
             }
        }).done(function(response){
             $("cities_dll").html(response);
        }); 
    });
    

    In the action:

    [HttpPost]
    public ActionResult getCicitesAction(int provinceId)
    {
         var cities = db.cities.Where(a => a.provinceId == provinceId).Select(a => "<option value='" + a.cityId + "'>" + a.cityName + "'</option>'";
    
         return Content(String.Join("", cities));
    }
    
    0 讨论(0)
提交回复
热议问题