使用ViewBag将模型传递到视图

6
我希望您能在我的视图中发送两个模型,在其他页面也可能需要更多。
控制器
ViewBag.Users = db.Users.ToList();

并且在视图中

@using Documentation.Models

@{
    var Users = (Documentation.Models.User)ViewBag.Users;
}

<table>
@foreach (var item in Users) {
    <tr>
        <td>
            @Html.DisplayFor(item.username)
        </td>
    </tr>
}
</table>

但是我没有得到任何答案,我知道我的代码有问题。 我遇到了这个错误。
 foreach statement cannot operate on variables of type 'Documentation.Models.User' because 'Documentation.Models.User' does not contain a public definition for 'GetEnumerator'

看起来你的代码有两个主要问题。就像@Peri提到的那样,你没有将其转换为用户容器。此外,我认为@Html.DisplayFor(item.username)会抛出一个错误,因为你没有使用像item => item.username这样的表达式,所以我建议你改用@Html.Display(item.username) =] - hae
我认为问题出在 @foreach (var item in Users) 或者 var Users = (Documentation.Models.User)ViewBag.Users; 中。 - Pnsadeghy
1个回答

11

你应该将ViewBag.Model强制转换为用户列表List<User>,而不是单个用户User。

@{
    var Users = (List<User>)ViewBag.Users;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接