尝试创建基于Car品牌和模型的级联下拉列表,但不幸的是,这些值不会显示在模型列表中。我在选择汽车品牌时得到了正确的反应,例如Bmw返回[" E30"," E46"," X5"]的JSON列表,但在SelectList中选项不会表现出来。
这里我返回JSON格式:
public JsonResult GetModels(int brandID)
{
String[] models;
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == brandID).Select(a=>a.Model_name).ToArray();
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
继承了用于显示模型的jQuery函数
$(document).ready(function () {
$("#brand_Brand_ID").change(function () {
// this will call when Brand Dropdown select change
var brandID = parseInt($("#brand_Brand_ID").val());
if (!isNaN(brandID)) {
var ddModel = $("#Model_ID");
ddModel.empty(); // this line is for clear all items from Model dropdown
ddModel.append($("<option></option").val("").html("Select model"));
$.ajax({
url: "@Url.Action("GetModels","ModelSpec")",
type: "GET",
data: { brandID: brandID },
dataType: "json",
success: function (data) { //here the data is always correct
$.each(data, function (i, val) {
ddModel.append(
$("<option></option>").val(val.Model_name).html(val.Model_name));
});
},
error: function () {
alert("Fail");
}
});
}
});
});
答案 0 :(得分:1)
您的代码应为
$.ajax({
url: "@Url.Action("GetModels","ModelSpec")",
type: "GET",
data: { brandID: brandID },
dataType: "json",
success: function (data) { //here the data is always correct
$.each(data, function (i, val) {
//use val as it returns array of string
ddModel.append(
$("<option></option>").val(val).html(val));
});
},
error: function () {
alert("Fail");
}
});