2011-03-09 53 views
6

我有一個由JSon加載的<select>。但我想用「@ html.dropdownlist helper」代替。我的JSON是:如何使用JSon填充@ html.dropdownlist mvc幫手

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

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

我希望我的代碼的可重用性和自我記錄。 如何使用dropdownlist將對象「site」從JSon發送到「cshtml」,以執行類似@html.dropdownlist(site.id, site.Nome)的操作???

有沒有辦法?

Tks guys。

回答

18

在你看來:

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

其中SiteId是您的視圖模型的屬性的表單提交時將接收選定的網站ID。

,然後你可以使用填充此下拉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) 
      ); 
     }); 
    }); 
}); 

和控制器的行動,將返回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); 
} 
+0

我應該怎麼做的情況下,我想,以填補下拉上加載本身? http://stackoverflow.com/questions/5389571/formcollection-not-containing-select-control-added-in-mvc-razor – Vijay 2011-03-22 10:19:14

+0

謝謝你Darin Dimitrov.It幫我 – 2014-03-18 11:29:46

+0

@darin如果有一個模型錯誤和它返回到視圖所選擇的選項對我來說已經消失了,我猜是因爲它在我搜索時按需加載。你知道如何解決這個問題嗎?在搜索要選擇的選擇之前,我必須鍵入3個字母 – 2016-05-02 21:54:23