How to populate mvc @ html.dropdownlist helper using JSon

I have a <select> that loads JSon. But instead I want to use "@ html.dropdownlist helper". My 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 populates it ...

 <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 to be more reusable and self-documenting. How can I send the site object from JSon to cshtml using the drop-down list to do something like @html.dropdownlist(site.id, site.Nome) ???

Is there any way?

Guys from Tks.

+6
json asp.net-mvc-3 razor
source share
1 answer

In your opinion:

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

where SiteId is the property of your view model that will receive the selected site identifier when submitting the form.

and then you can populate this dropdown with 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 controller actions that return 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); } 
+18
source share