我在另一个下拉列表的 on change 事件上创建了我的 Select,所以这是我的脚本:
$ddlOther.on('change', function(e) {
var Json = {},
persons = [];
Json.id = $(this).val();
$.post('/PersonController/GetPersonDDL', Json, function(data) {
drivers = data;
}, 'json').done(function(data) {
$person.select2({
placeholder: "Select Persons(s)",
allowClear: true,
multiple: true,
data: persons
});
});
});
这是我的控制器方法:
public ActionResult GetPersonDDL(JsonDictionary args)
{
JsonResult result = null;
string id= args["id"].Trim();
var persons = _context.Persons
.Where(x => x.id== id)
.Select(x => new
{ x.first_name,
x.middle_name,
x.last_name, x.id
}).ToList();
foreach (var person in persons)
{
var item = new SelectListItem
{
Text = string.Format("{0} - {1} {2} {3}",
person.id,
person.first_name,
person.middle_name,
person.last_name),
Value = person.id
};
list.Add(item);
}
result = Json(list.Select(x=>new {value = x.Text,
id = x.Value}
), JsonRequestBehavior.AllowGet);
return result;
}
我取回数据,但控制台(在这种情况下为萤火虫)给了我错误:
TypeError: a is undefined
返回的JSON
样子是这样的:
[
Object { value="John Doe", id="1"},
Object { value="Jane Doe" id="2"}
]