Trong ViewModel của tôi, tôi có:ASP.NET MVC + cư DropDownList
public class PersonViewModel
{
public Person Person { get; set; }
public int SelectRegionId { get; set; }
public IEnumerable<SelectListItem> Regions { get; set; }
}
Nhưng tôi phải làm gì phải làm trong tôi Controller/Xem để hiển thị các giá trị? Những gì tôi có bây giờ:
Bộ điều khiển:
public ActionResult Create()
{
var model = new ReUzze.Models.PersonViewModel
{
Person = new Person(),
Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
};
return View(model);
}
Xem:
<div class="form-group">
@Html.LabelFor(model => model.Person.Address.Region)
@Html.DropDownListFor(model => model.SelectRegionId, new SelectList(Model.Regions, "Id", "Name"), "Choose... ")
</div>
Nhưng nó mang lại cho một lỗi như thế này:
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?)
Bạn có thể thêm các thông báo lỗi bạn nhận được? – MattC
Thuộc tính Khu vực trong mô hình phải là danh sách các mục bình thường. Đừng đặt nó vào SelectList. – Slavo
Bạn thậm chí có thể sử dụng ViewBag để gửi dữ liệu trong danh sách theo cách để xem và sau đó ràng buộc danh sách thả xuống với nó. Xem http://www.yogihosting.com/blog/populate-dropdownlist-with-dynamic-values-in-asp-net-mvc/ – yogihosting