How to populate a @html.dropdownlist mvc helper using JSon

邮差的信 提交于 2019-12-18 16:57:33

问题


I have a <select> which is loaded by a JSon. But I want to use "@html.dropdownlist helper" instead. My Json is:

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...

<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)???

Is there a way?

Tks guys.


回答1:


In your view:

@Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))

where SiteId is a property of your view model which will receive the selected site id when the form is submitted.

and then you could populate this dropdown using 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:

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);
}


来源:https://stackoverflow.com/questions/5246590/how-to-populate-a-html-dropdownlist-mvc-helper-using-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!