在我的viewModel中我有:
public class PersonViewModel
{
public Person Person { get; set; }
public int SelectRegionId { get; set; }
public IEnumerable<SelectListItem> Regions { get; set; }
}
但是我在Controller / View中需要做些什么来显示值?我现在拥有的:
的控制器:
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 :(得分:13)
您的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>
答案 1 :(得分:7)
您正在创建两次SelectList实例。摆脱其中一个:
@Html.DropDownListFor(model => model.SelectRegionId, Model.Regions, "Choose... ")