6

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.

Thiago
  • 1,547
  • 3
  • 25
  • 40

1 Answers1

18

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);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • What should I do in case I want to fill dropdown on load itself? http://stackoverflow.com/questions/5389571/formcollection-not-containing-select-control-added-in-mvc-razor – Vijay Mar 22 '11 at 10:19
  • Thank You Darin Dimitrov.It helpes me – kavitha Reddy Mar 18 '14 at 11:29
  • @darin If there is a model error and it returns to the view the selected option is gone for me I guess because it is loaded on demand for me when I search. Do you know how to fix that? I have to type 3 letters before it searches for a selection to choose – Devin Prejean May 02 '16 at 21:54