gpt4 book ai didi

c# - 刷新 MVC 下拉列表

转载 作者:行者123 更新时间:2023-11-30 16:52:57 25 4
gpt4 key购买 nike

我想通过 JsonResult 方法刷新 MVC 下拉列表。

这是返回结果的公共(public)方法:

    [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 并使用刷新 html$('.applicationSelector').html(数据); ?

最佳答案

您需要附加一个 <option>对于每个项目。这是取自 this post 的答案它提供了一个非常简单直接的示例。

$.each(selectValues, function(key, value) {   
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});

其中 var selectValues 是您的 JSON 列表

关于c# - 刷新 MVC 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com