C# 使用AJAX MVC 4填充DropDownList
我有一个包含2@DropDownListFor的助手的视图:C# 使用AJAX MVC 4填充DropDownList,c#,jquery,ajax,asp.net-mvc,C#,Jquery,Ajax,Asp.net Mvc,我有一个包含2@DropDownListFor的助手的视图: @using (Html.BeginForm("CreateOneWayTrip", "Trips")) { @Html.ValidationSummary(false); <fieldset> <legend>Enter Your Trip Details</legend> <label>
@using (Html.BeginForm("CreateOneWayTrip", "Trips"))
{
@Html.ValidationSummary(false);
<fieldset>
<legend>Enter Your Trip Details</legend>
<label>Start Point</label>
@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" })
<p style="float: none; text-align: center;">
<button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
<i class="fa fa-check"></i>
</button>
<button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
<i class="fa fa-times"></i>
</button>
</p>
</fieldset>
}
创建页面时,将填充其中一个DropsDownList,并根据用户在第一个DropDownList中选择的选项填充第二个DropsDownList。为了实现这一点,我正在使用ajax。我使用的javascript如下所示:
$(“#省#dll”).change(函数(){
$.ajax({
url:'getCities/Trips',
键入:“post”,
数据:{
provinceId:$(“#省dll”).val()
}
}).完成(功能(响应){
$(“cities_dll”).html(回复);
});
});代码>您可以尝试以下方法吗
这是我几天前回复的帖子。
字体:
您应该在省ddl的更改事件中创建一个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 => "<option value='" + a.cityId + "'>" + a.cityName + "'</option>'";
return Content(String.Join("", cities));
}
[HttpPost]
公共行动结果getCicitesAction(int provinceId)
{
var cities=db.cities.Where(a=>a.provinceId==provinceId)。选择(a=>“”+a.cityName+“”);
返回内容(String.Join(“,cities));
}
获取字符串集合的原因是System.Web.Mvc.SelectListItemSystem
是var lstCities=new SelectList(new[]{“City1”、“City2”、“City3”);
返回IEnumerable
和String.Join(“,lstCities)
调用.ToString()
返回“System.Web.Mvc.SelectListItemSystem”
的集合中每个SelectListItem
项的方法(不是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 code you have shown
var cities = new List<string>() { "City1", "City2", "City3" });
return Json(cities, JsonRequestBehavior.AllowGet);
}
编辑
除了OP的注释之外,如果数据库包含一个表名Cities
,带有字段ID
和name
,那么控制器方法如下
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));
});
$。每个(响应、函数(索引、项){//item现在是一个包含属性ID和文本的对象
cities.append($('').text(item.text).val(item.ID));
});
让我们把它变得更简单
- 步骤1:服务器端功能/数据
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);
}
- 步骤3:调用-客户端功能/启动
- 清单1:
@Html.DropDownList("ODD", ViewBag.OList as IEnumerable<SelectListItem>, new { @id = "ODD", @class = "form-control", @onchange= "FetchP()" })
@Html.DropDownList(“ODD”、ViewBag.OList作为IEnumerable、新的{@id=“ODD”、@class=“form control”、@onchange=“FetchP()”})
- 清单2:
@Html.DropDownList("PDD", ViewBag.PList as IEnumerable<SelectListItem>,new { @id = "PDD", @class = "form-control"})
@Html.DropDownList(“PDD”,ViewBag.PList作为IEnumerable,新的{@id=“PDD”,@class=“form control”})
在getCities操作中,能否将“var options=String.Join(“,lstCities”);返回内容(options);”替换为“返回内容(String.Join(“,lstCities”);“然后在返回前检查选项变量以查看它存储了什么?我尝试使用此javascript,但仍然没有骰子。我将#city_dll和#province_dll替换为StartPointCity和StartPointProvince。我遗漏了什么吗?注意#city_dll
如果删除了新的,则需要将其替换为#StartPointCity
{id=“city_dll”}
。如果它不起作用,请打开浏览器控制台并检查是否有错误。在脚本上放置一个断点,然后逐步调试和/或添加console.log()
检查变量值的语句我将#city_dll
更改为#StartPointCity
原因是,我在控制器中放置了一个断点,该断点应返回JsonResult
,当我在#StartPointProvince
下拉列表中选择一个值时,它没有到达断点。我有ted代码和它的工作。把一个断点在脚本中使用您的浏览器工具,并逐步通过它。这对我来说是有效的,除了我必须使用:cities.append($('').text(item.text).val(item.ID));
在步骤2的末尾缺少右括号
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);
});
});
}
@Html.DropDownList("ODD", ViewBag.OList as IEnumerable<SelectListItem>, new { @id = "ODD", @class = "form-control", @onchange= "FetchP()" })
@Html.DropDownList("PDD", ViewBag.PList as IEnumerable<SelectListItem>,new { @id = "PDD", @class = "form-control"})