【问题标题】:ASP.NET MVC + Populate dropdownlistASP.NET MVC + 填充下拉列表
【发布时间】:2014-01-01 06:32:44
【问题描述】:

在我的 viewModel 中,我有:

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?)

【问题讨论】:

  • 你能添加你收到的错误信息吗?
  • 模型中的 Regions 属性应该是正常的项目列表。不要将其设置为 SelectList。

标签: c# asp.net asp.net-mvc asp.net-mvc-4 html.dropdownlistfor


【解决方案1】:

您的 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>

【讨论】:

    【解决方案2】:

    您正在创建 SelectList 实例两次。摆脱其中之一:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多