在我的MVC 4应用程序中,我想用Ajax结果填充Html.LisboxFor。
我的观点: @using(Html.BeginForm(“UpdatePriority”,“Priority”,FormMethod.Post)) {
@Html.Hidden("myListBoxValuesValues")
<div class="row">
<div class="col-md-2">
<label>FA:</label>
@Html.ListBoxFor(m => m.FA, new MultiSelectList(@Model.FA), new { @class = "lbx_FA" })
</div>
<div class="col-md-1">
<input id="btnAdd" type="button" value=" > " onclick="addItem();" />
</div>
<div class="col-md-2">
<label>CEID list:</label>
@Html.ListBoxFor(model => model.CEIDs, new MultiSelectList(Model.CEIDs), new { @class = "lbx_CEIDs" })
</div>
...and so on..
我的控制器功能(返回json模型的字符串):
public string getCeidPerFA(string FA)
{
return unitOfWork.ToolRequiredRepository.getCEIDsPerFA_Scenario(DAL.UnitOfWork.Scenario, FA);
}
存储库功能:
internal string getCEIDsPerFA_Scenario(string scenario, string FA)
{
//create the result list (FAs):
List<string> FAs = FA.Split(',').ToList();
var CEIDs = from row in context.ToolRequireds
where row.Scenario == scenario && FAs.Contains(row.FA)
select row.CEID;
List<string> lst = CEIDs.Distinct().ToList();
//create Json Result:
List<SelectListItem> items = new List<SelectListItem>();
foreach (var ceid in lst)
{
items.Add(new SelectListItem { Text = ceid, Value = ceid });
}
return Json.Encode(items);
}
我的剧本:
function addItem() {
var result = "";
var x = document.getElementById("FA");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
result += x.options[i].value + ",";
}
}
result = result.substring(0, result.length - 1);
$.ajax({
url: "@(Url.Action("getCeidPerFA", "CeidSelection"))",
data: { "FA": result },
success: function (data) {
if (data.length > 0) {
JSON.pa
$("#CEIDs").append(JSON.parse(data));
}
else
alert("No Result");
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
我的代码错了,但我不知道该怎么做。 任何帮助将非常感激。
答案 0 :(得分:3)
像这样循环遍历数据结果
$('#CEIDs').empty();
$.each($(data), function(key, value) {
$('#CEIDs').append('<option value=' + key + '>' + value + '</option>');
});