使用AJAX MVC 4填充DropDownList

我有一个包含2 @ DropDownListFor的助手的视图:

@using (Html.BeginForm("CreateOneWayTrip", "Trips")) { @Html.ValidationSummary(false); 
Enter Your Trip Details @Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces, new { @Id = "province_dll", @class = "form-control" }) @Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities, new { @Id = "city_dll", @class = "form-control" })

}

这是我用来捕获数据的临时模型:

  public class CaptureCreateTrip { [Required] [Display(Name = "Trip ID")] public string TripID { get; set; } [Required] public string StartPointProvince { get; set; } [Required] public string StartPointCity { get; set; } } 

创建页面时会填充其中一个DropsDownList,而第二个将根据用户在第一个DropDownList中选择的选项进行填充。 为实现这一目标,我正在使用ajax。 我使用的javascript看起来像这样:

 $("#province_dll").change(function () { $.ajax({ url: 'getCities/Trips', type: 'post', data: { provinceId: $("#province_dll").val() } }).done(function (response) { $("cities_dll").html(response); }); }); 

这是AJAX调用的Controller:

  [HttpPost] public ActionResult getCicites(int provinceId) { var lstCities = new SelectList(new[] { "City1", "City2", "City3" }); return Content(String.Join("", lstCities)); } 

到目前为止一切正常 – 当我在省DropDown中选择一个值时,javascript事件会触发,而Controller操作会将选择列表值返回到Cities DropDown,但问题是数据(格式为数据) Action返回不正确。 我通过创建一个Paragraph元素并使用ajax调用的返回值更新它的文本来测试它,即:“System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.Select ListItem”

*注意:我是ajax的新手,在学习Jquery和AJAX的过程中。

你获得字符串var lstCities = new SelectList(new[] { "City1", "City2", "City3" }); "System.Web.Mvc.SelectListItemSystem"var lstCities = new SelectList(new[] { "City1", "City2", "City3" }); 返回IEnumerableString.Join("", lstCities)调用集合中每个SelectListItem项的.ToString()方法,返回"System.Web.Mvc.SelectListItemSystem" (不是SelectListItemText属性的值) )

填充第二个下拉列表的最佳方法是返回包含城市集合的json,并在ajax成功回调中更新DOM。 没有理由创建一个SelectList – 它只是不必要的额外开销,并且你必须将至少3倍的数据返回给客户端(客户端没有C# SelectListItem类的概念)。

 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() { "City1", "City2", "City3" }); return Json(cities, JsonRequestBehavior.AllowGet); } 

然后在脚本中(不知道为什么你已经将id="StartPointProvince"的默认id修改为id="province_dll" ,但是)

 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($('').text(item)); }); }); }); 

编辑

继OP的评论之后,如果数据库包含一个表名为Cities with fields IDName ,那么控制器方法就是这样的

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

并且创建选项的脚本将是

 $.each(response, function(index, item) { // item is now an object containing properties ID and Text cities.append($('').text(item.Text).val(item.ID)); }); 

你可以试试以下吗?

这是我几天前发帖的post。 字体: 动态DropDownLists在MVC 4表格中

您应该在省ddl的change事件中创建一个ajax调用。 此呼叫将请求某个操作并返回所选省份的城市。

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

在行动中:

 [HttpPost] public ActionResult getCicitesAction(int provinceId) { var cities = db.cities.Where(a => a.provinceId == provinceId).Select(a => "'"; return Content(String.Join("", cities)); } 

让它变得更简单

  • 第1步:服务器端function/数据

     public JsonResult FetchP(string O) { List PList = new List(); PList = _PService.GetAllPActive() .Select(i => new SelectListItem() { Text = i.PName, Value = i.PID }).ToList(); return Json(PList, JsonRequestBehavior.AllowGet); } 
  • 第2步:客户端function/数据解释器

     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); }); }); } 
  • 第3步:呼叫 – 客户端function/启动

  • 清单1:

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

     @Html.DropDownList("PDD", ViewBag.PList as IEnumerable,new { @id = "PDD", @class = "form-control"})