如何使用JSon填充@html.dropdownlist mvc帮助程序
我有一个由JSon加载的如何使用JSon填充@html.dropdownlist mvc帮助程序,json,asp.net-mvc-3,razor,Json,Asp.net Mvc 3,Razor,我有一个由JSon加载的。但是我想用“@html.dropdownlist helper”来代替。我的Json是: function LoadSites() { $("SelectSite").html(""); $.getJSON("/Pedido/GetSite", null, function (data) { $("#SelectSite").append("<option value=0>Selecione...</option>"); $.ea
。但是我想用“@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>");
});
});
函数加载站点(){
$(“SelectSite”).html(“”);
$.getJSON(“/Pedido/GetSite”),null,函数(数据){
$(“#SelectSite”).append(“Selecione…”);
$.each(数据、结果、功能(索引、站点){
$(“#SelectSite”).append(“+site.Nome+”);
});
});
这个Json填充了这个
<select id="SelectSite"></select>
我的控制器:
[HttpGet]
public JsonResult GetSite()
{
Repository<Site> siteRepo = new Repository<Site>( unitOfWork.Session );
return this.Json( new { Result = siteRepo.All() }, JsonRequestBehavior.AllowGet );
}
[HttpGet]
public JsonResult GetSite()
{
Repository siteRepo=新存储库(unitOfWork.Session);
返回this.Json(新的{Result=siteRepo.All()},JsonRequestBehavior.AllowGet);
}
我希望我的代码更加可重用和自文档化。
如何使用dropdownlist将对象“site”从JSon发送到“cshtml”以执行类似于@html.dropdownlist(site.id,site.Nome)
有办法吗
Tks伙计们。在你看来:
@Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))
以及将返回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);
}
如果我想在加载时填充下拉列表,我应该怎么做?谢谢Darin Dimitrov。它很有用me@darin如果出现模型错误并返回到视图,我想所选选项将消失,因为它是在我搜索时根据需要加载的。你知道如何修复吗?我必须键入3个字母,然后它才能搜索所选内容选择
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);
}