asp.net-mvc ASP.NET MVC Html.DropDownList 由 Ajax 调用填充到控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3830099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC Html.DropDownList populated by Ajax call to controller?
提问by UpTheCreek
I wanted to create an editor template for a field type that is represented as a dropdownlist. In the definition of the editor template I would like to populate the DropDownList using a call to an action on the controller returning the results as JSON - Any ideas how to do this?
我想为表示为下拉列表的字段类型创建一个编辑器模板。在编辑器模板的定义中,我想使用对控制器上的操作的调用来填充 DropDownList,将结果作为 JSON 返回 - 任何想法如何做到这一点?
E.g something like:
例如:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TheFieldType>" %>
<%= Html.DropDownList(.....
回答by Darin Dimitrov
In the editor template provide an empty dropdown:
在编辑器模板中提供一个空的下拉列表:
<%= Html.DropDownListFor(
x => x.PropertyToHoldSelectedValue,
Enumerable.Empty<SelectListItem>(),
"-- Loading Values --",
new { id = "foo" })
%>
Then setup a controller action that will return the values:
然后设置一个将返回值的控制器操作:
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);
}
}
And then populate the values using AJAX:
然后使用 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);
});
});
});
回答by Frank Bonnet
I know this post is a few years old but I found it and so might you. I use the following solution and it works very well. Strong typed without the need to write a single line of Javascript.
我知道这篇文章已经有几年了,但我找到了它,你也一样。我使用以下解决方案,效果很好。强类型无需编写一行 Javascript。
mvc4ajaxdropdownlist.codeplex.com
mvc4ajaxdropdownlist.codeplex.com
You can download it via Visual Studio as a NuGet package.
您可以通过 Visual Studio 将其下载为 NuGet 包。