gpt4 book ai didi

asp.net-mvc - ASP.NET MVC Html.DropDownList 由对 Controller 的 Ajax 调用填充?

转载 作者:行者123 更新时间:2023-12-03 13:38:59 25 4
gpt4 key购买 nike

我想为表示为下拉列表的字段类型创建一个编辑器模板。在编辑器模板的定义中,我想使用对 Controller 上的操作的调用来填充 DropDownList,将结果作为 JSON 返回 - 任何想法如何做到这一点?

例如:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TheFieldType>" %>
<%= Html.DropDownList(.....

最佳答案

在编辑器模板中提供一个空的下拉菜单:

<%= Html.DropDownListFor(
x => x.PropertyToHoldSelectedValue,
Enumerable.Empty<SelectListItem>(),
"-- Loading Values --",
new { id = "foo" })
%>

然后设置一个将返回值的 Controller 操作:
public class FooController: Controller
{
public ActionResult Index()
{
return Json(new[] {
new { Id = 1, Value = "value 1" },
new { Id = 2, Value = "value 2" },
new { Id = 3, Value = "value 3" },
}, JsonRequestBehavior.AllowGet);
}
}

然后使用 AJAX 填充值:
$(function() {
$.getJSON('/foo/index', function(result) {
var ddl = $('#foo');
ddl.empty();
$(result).each(function() {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
});
});

关于asp.net-mvc - ASP.NET MVC Html.DropDownList 由对 Controller 的 Ajax 调用填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3830099/

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