2013-12-13 166 views
10

在我的ViewModel我有:ASP.NET MVC +填充DROPDOWNLIST

public class PersonViewModel 
{ 
    public Person Person { get; set; } 
    public int SelectRegionId { get; set; } 
    public IEnumerable<SelectListItem> Regions { get; set; } 
} 

但是我有我的控制器/視圖執行,以顯示值是多少?我現在擁有的一切:
控制器:

public ActionResult Create() 
{ 
    var model = new ReUzze.Models.PersonViewModel 
    { 
     Person = new Person(), 
     Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name") 
    }; 
    return View(model); 
} 

查看:

<div class="form-group"> 
    @Html.LabelFor(model => model.Person.Address.Region) 
    @Html.DropDownListFor(model => model.SelectRegionId, new SelectList(Model.Regions, "Id", "Name"), "Choose... ") 
</div> 

但它給這樣的錯誤:

Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.IEnumerable<System.Web.WebPages.Html.SelectListItem>'. An explicit conversion exists (are you missing a cast?) 
+0

你可以添加您收到錯誤消息? – MattC

+0

模型中的Regions屬性應該是正常的項目列表。不要將其設置爲SelectList。 – Slavo

+0

您甚至可以使用ViewBag以列表方式將數據發送到視圖,然後使用它綁定下拉列表。見http://www.yogihosting.com/blog/populate-dropdownlist-with-dynamic-values-in-asp-net-mvc/ – yogihosting

回答

12

您的ViewModel具有'IEnumerable'類型的屬性,但SelectList不滿足該類型。 更改您這樣的代碼:

public class PersonViewModel 
{ 
    public Person Person { get; set; } 
    public int SelectRegionId { get; set; } 
    public SelectList Regions { get; set; } 
} 

查看:

<div class="form-group"> 
    @Html.LabelFor(model => model.Person.Address.Region) 
    @Html.DropDownListFor(model => model.SelectRegionId, Model.Regions, "Choose... ") 
</div> 
7

你兩次創建的SelectList實例。擺脫其中之一:

@Html.DropDownListFor(model => model.SelectRegionId, Model.Regions, "Choose... ")