2016-10-05 2 views
0

У меня есть два выпадающих списка в названии State и City .. при выборе State необходимо отобразить соответствующие города, но не удалось извлечь CityId и CityName For City DropDown.MVC 5 DropDownList OnSelect Change

Контроллер

public JsonResult cities(int state, Employee employee) 
{ 
    var cities = new SelectList(db.Cities.Where(c => c.StateId == state), "CityId", "CityName", employee.City); 
    return Json(cities,JsonRequestBehavior.AllowGet); 
} 

Jquery

<script> 
    $(document).ready(function() { 
     $("#City").prop("disabled", true); 
     $("#State").change(function() { 
      if ($("#State").val() != 1) { 
       var StateOptions = {}; 
       StateOptions.url = "/Employees/cities"; 
       StateOptions.type = "POST"; 
       StateOptions.data = JSON.stringify({ State: $("#State").val() }); 
       StateOptions.datatype = "json"; 
       StateOptions.contentType = "application/json"; 
       StateOptions.success = function (CitysList) { 
        $("#City").empty(); 
        for (var i = 0; i < CitysList.length; i++) { 

       // Unable to extract CityID and CityName in option here 

         $("#City").append("<option value=" + CitysList[i] + ">" + CitysList[i] + "</option>"); 
        } 
        $("#City").prop("disabled", false); 
       }; 
       StateOptions.error = function() { alert("Error in Getting Citys!!"); }; 
       $.ajax(StateOptions); 
      } 
      else { 
       $("#City").empty(); 
       $("#City").prop("disabled", true); 
      } 
     }); 
    }); 
</script> 

Это государственные и городские Dropdowns в View .........

<div class="form-group"> 
      @Html.LabelFor(model => model.State, "State", htmlAttributes: new { @class = "control-label col-md-2"}) 
      <div class="col-md-10"> 
       @Html.DropDownList("State", null, htmlAttributes: new { @class = "form-control"}) 
       @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.City, "City", htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownList("City", new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"), "Select City", htmlAttributes: new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
+0

Получение объекта в качестве ответа. но не смог извлечь имя города и города. –

+0

'CitysList [i] .Value' и' CitysList [i] .Text' Но вы не должны возвращать 'SelectList'. Просто верните коллекцию анонимных объектов, содержащих только 2 свойства, которые вам нужны. - 'var cities = db.Cities.Where (c => c.StateId == state). Выбрать (c => new {Value = c.CityId.ToString(), Text = c.CityName});' –

+0

И просто используйте '.data = {State: $ (" # State "). val()}; и удалите 'StateOptions.contentType =" application/json ";' и удалите параметр Employee employee из вашего метода –

ответ

0
var stId = $("#State").val(); StateOptions.data = { state: stId }; 

удалить сотрудника сотрудника, потому что вы не отправляете это значение.

удалить этот StateOptions.contentType = "application/json";

изменить способ, как этот

public JsonResult cities(int state) 
{ 
     var cities = (from city in db.Cities where city.StateId == state select new CityModel 
        { 
         CityId = city.CityId, CityName = city.CityName 
        }).ToList(); 
     return Json(cities,JsonRequestBehavior.AllowGet); 
} 

свой АЯКС вызов успеха, как этот

success: function (CitysList) { 
     $.each(CitysList, function (i, val) 
     {  
       $('#City').append($("<option/>", ($({ value: val.CityId, text: val.CityName })))); 
     }); 
}, 
Смежные вопросы