【发布时间】:2016-04-17 02:47:21
【问题描述】:
下面是我的代码,我不知道我做错了什么?
ajax json jquery 代码
function FillCity() {
var countryid = $("select[name$='.countryid']").val(); //<---- this is dynamic
$.ajax({
url: "Controller/FillMyCity",
type: "POST",
dataType: "json",
data: { country: countryid } ,
success: function (city) {
$("select[name$='.cityid']").html(""); // <--- this is dynamic
$.each(city, function (i, pp) {
$("select[name$='.cityid']").append(
$('<option></option>').val(pp.cityid).html(pp.name));
});
},
error: function (err) {
alert(err);
}
});
}
控制器方法
public JsonResult FillMyCity(int country)
{
var cities = db.Cities.Where(x => x.countryid == country).ToList().Select(item => new City
{
cityid = item.cityid,
name = item.name
}).AsQueryable();
return Json(cities, JsonRequestBehavior.AllowGet);
}
查看
@Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { @class = "form-control countries", @id = "mycountry" + i + "", @onchange = "FillCity()" })
@Html.DropDownList("City[" + i + "].cityid", new SelectList(Enumerable.Empty<SelectListItem>(), "cityid", "name"), "Select city", new { @class = "form-control cities", @id = "mycity" + i + "" })
输出
EmployeeName Country City
Jenny ddl of countries ddl of cities
John ddl of countries ddl of cities
问题 1:当我为 Jenny 选择国家时,Jenny + John 的城市 ddl 都填充了 Jenny's Country 的城市,但它应该只适用于 Jenny。当我为约翰选择国家时,城市 ddl 列表不会被填充所以只有珍妮的作品,约翰没有
问题2:由于它是动态的json jquery附加html,我无法保存city值,这是因为它是动态的并且不会出现在视图源中。
【问题讨论】:
-
您应该更具体地清除自己...您的确切问题是什么?
-
@Md.MostafizurRahman 我上面提到的问题是,当我为珍妮选择一个国家时,该国家的城市也会为约翰的城市的 ddl 填充?它应该只适用于珍妮。我说的另一个问题是无法将“城市”保存到数据库,因为它是动态的。谢谢
标签: c# jquery json ajax asp.net-mvc