ASP.NET MVC 5中的下拉列表填充错误

时间:2019-03-09 19:05:49

标签: asp.net-mvc

我的控制器中包含以下内容:

public ActionResult Create()
{
    ViewBag.PlayerId = new SelectList(db.Players, "Id", "Name");
    return View();
}  

这在视图中:

<div class="form-group">
    @Html.LabelFor(model => model.PlayerId, "PlayerId", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
            @Html.DropDownList("PlayerId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.PlayerId, "", new { @class = "text-danger" })
    </div>
</div>  

但是当我提交表单时,它给了我以下错误:

  

System.InvalidOperationException:“具有键“ PlayerId”的ViewData项的类型为“ System.Int32”,但必须类型为“ IEnumerable”。”

我在Google上搜索了很多,但是找不到解决方案。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

编写您的@Html.DropDownList如下:

@Html.DropDownList("PlayerId", ViewBag.PlayerId as SelectList,"Select Player", htmlAttributes: new { @class = "form-control" })

现在可以使用了!

答案 1 :(得分:0)

您必须将SelectList传递到下拉列表中,但实际上,模型绑定器在PlayerId作为viewmodel属性和PlayerId作为ViewBag属性之间是混淆的,因此会导致错误。

更好地创建一个viewmodel属性,该属性将存储具有不同名称的选项列表:

public class ViewModel
{
    public int PlayerId { get; set; }

    // other properties

    // option list here
    public List<SelectListItem> PlayerList { get; set; }
}

然后将数据库中的选项列表添加到控制器操作中:

public ActionResult Create()
{
    var model = new ViewModel();
    model.PlayerList = db.Players.Select(x => new SelectListItem { Text = x.Name, Value = x.Id }).ToList();
    return View(model);
}

然后使用强类型助手将其绑定:

@Html.DropDownListFor(model => model.PlayerId, Model.PlayerList, "Select", new { @class = "form-control" })

相关问题:

The ViewData item that has the key is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'