如何使用 Json 填充 @html.dropdownlist mvc 助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5246590/
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
How to populate a @html.dropdownlist mvc helper using JSon
提问by Thiago
I have a <select>which is loaded by a JSon. But I want to use "@html.dropdownlist helper" instead. My Json is:
我有一个<select>由 JSon 加载的。但我想改用“@html.dropdownlist helper”。我的 Json 是:
function LoadSites() {
$("SelectSite").html("");
$.getJSON("/Pedido/GetSite", null, function (data) {
$("#SelectSite").append("<option value=0>Selecione...</option>");
$.each(data.Result, function (index, site) {
$("#SelectSite").append("<option value='" + site.Id + "'>" + site.Nome + "</option>");
});
});
this Json populate this...
这个Json填充这个......
<select id="SelectSite"></select>
My Controller:
我的控制器:
[HttpGet]
public JsonResult GetSite()
{
Repository<Site> siteRepo = new Repository<Site>( unitOfWork.Session );
return this.Json( new { Result = siteRepo.All() }, JsonRequestBehavior.AllowGet );
}
I want my code more reusable and self-documenting.
How can I send the object "site" from JSon to "cshtml" using dropdownlist to do something like @html.dropdownlist(site.id, site.Nome)???
我希望我的代码更具可重用性和自我记录性。如何使用下拉列表将对象“站点”从 JSon 发送到“cshtml”来执行类似的操作@html.dropdownlist(site.id, site.Nome)???
Is there a way?
有办法吗?
Tks guys.
伙计们。
回答by Darin Dimitrov
In your view:
在您看来:
@Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))
where SiteIdis a property of your view model which will receive the selected site id when the form is submitted.
whereSiteId是您的视图模型的属性,它将在提交表单时接收选定的站点 ID。
and then you could populate this dropdown using AJAX:
然后你可以使用 AJAX 填充这个下拉列表:
$(function() {
$.getJSON('@Url.Action("GetSite", "Pedido")', function(result) {
var ddl = $('#SiteId');
ddl.empty();
$(result).each(function() {
ddl.append(
$('<option/>', {
value: this.Id
}).html(this.Nome)
);
});
});
});
and the controller action that would return the JSON data:
以及将返回 JSON 数据的控制器操作:
public ActionResult GetSite()
{
var sites = new[]
{
new { Id = "1", Nome = "site 1" },
new { Id = "2", Nome = "site 3" },
new { Id = "3", Nome = "site 3" },
};
return Json(sites, JsonRequestBehavior.AllowGet);
}

