您获取字符串的原因
"System.Web.Mvc.SelectListItemSystem"是,该方法
var lstCities = newSelectList(new[] { "City1", "City2", "City3"});返回IEnumerable<SelectListItem>并
String.Join("",lstCities)调用返回的集合.ToString()中每个
SelectListItem项目的方法
"System.Web.Mvc.SelectListItemSystem"(而不是的
Text属性值
SelectListItem)
填充第二个下拉列表的最佳方法是返回包含城市集合的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 pre you have shown var cities = new List<string>() { "City1", "City2", "City3" }); return Json(cities, JsonRequestBehavior.AllowGet);}然后在脚本中(不确定为什么将默认值
id从修改
id="StartPointProvince"为
id="province_dll",但是)
var url = '@Url.Action("FetchCities", "Trips")'; // Don't hard pre 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)); }); });});编辑
除了OP的注释,如果数据库包含
Cities带有字段
ID和的表名
Name,则controller方法将类似于
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($('<option></option>').text(item.Text).val(item.ID));});


