ASP.NET MVC 4 中的 ViewBag

ViewBag in ASP.NET MVC 4

我在使用ViewBag 向View 传递数据时遇到了麻烦。 我有一个模型,名称为:"Place"。它包含 {PlaceId, Name, Description, National, Area, Provience, MapKey}

在控制器的动作中。我需要将 "Place" 模型的 {PlaceId, Name} 传递给 select 选项。这是我的代码:

+在视图中:

    <select class="form-control" id="Place" name="PlaceId" title="Chose a place">
                @foreach (var item in ViewBag.list)
                {
                    <option value="@item.PlaceId">@item.Name</option>
                }
    </select>

我在这里遇到了错误。此错误是:'object' 不包含 'PlaceId'

的定义

错误的原因是您将匿名对象的集合传递给了视图。 This article 详细解释了问题,但转述

Anonymous objects are internal by default, meaning they are only accessible to the assembly in which they were created. Once you cross that assembly boundary, it gets treated as a regular object, which does not have the PlaceId property

正确的方法是将集合分配给视图模型中的 SelectList(或 IEnumerable<SelectListItem>)属性,或分配给 ViewBag.

例如,使用视图模型

public SelectList PlacesList { get; set; }

并在控制器中

model.PlacesList = new SelectList(db.Places, "PlaceId", "Name");

然后在视图中

@Html.DropDownListFor(m => m.yourProperty, Model.PlacesList)