我希望能够通过一个JsonResult方法刷新MVC下拉列表。
以下是返回结果的公共方法:
[HttpPost]
[ValidateAntiForgeryToken]
[CustomAuthorize]
public JsonResult GetHtmlApplicationSelectionList()
{
try
{
List<SelectListItem> applicationList = new List<SelectListItem>();
SelectListItem defaultApplicationValue = new SelectListItem();
defaultApplicationValue.Value = "0";
defaultApplicationValue.Text = "-- Select Application --";
defaultApplicationValue.Selected = true;
applicationList.Add(defaultApplicationValue);
foreach (var app in businessLogic.GetApplications().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Name }))
{
applicationList.Add(app);
}
return Json(new { result = "success", list = applicationList }, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json(new { result = "failure", message=ex.Message}, JsonRequestBehavior.AllowGet);
}
}
以下是调用POST方法获取更新的应用程序列表的jQuery函数:
function UpdateApplicationList() {
$.ajax({
url: 'Global/GetHtmlApplicationSelectionList',
type: 'POST',
dataType: 'json',
success: function (data) {
$('.applicationSelector').html('');
$('.applicationSelector').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
}
如何强制使$(.applicationSelector')下拉列表包含新列表,而无需遍历作为JSON返回的列表?是否可以返回列表(applicationList)的html,并只使用$('.applicationSelector').html(data)刷新html?