【问题标题】:foreach() over List<T> in ViewBag recognizes T as object instead of actual typeViewBag 中 List<T> 上的 foreach() 将 T 识别为对象而不是实际类型
【发布时间】:2015-06-10 09:58:21
【问题描述】:

我收到这个奇怪的错误,Razor 会说对象中不存在属性。我觉得我犯了一个愚蠢的错误,但我已经为此奋斗了一段时间,但没有运气。有什么线索吗?

控制器方法:

List<Conversations> lConversations = usr.conversations.OrderBy(o => o.active).ThenByDescending(o => o.updated_at).ToList().Select(i => new Conversations
{
    Created = i.created_at, Creator = string.Format("{0} {1}", i.user.first_name, i.user.last_name), Name = i.name, Status = (i.active) ? "Active" : "Deactivated", TotalUsers = i.message_recipient.Count(c => c.active)
}).ToList();

ViewBag.conversations = lConversations;

在视图文件中,我尝试遍历对象并打印出数据。

@foreach (var i in ViewBag.conversations)
{
    <tr>
        <td>@i.Name</td>
        <td>@i.TotalUsers</td>
        <td>@i.Creator</td>
        <td>@i.Status</td>
        <td>@i.Created</td>
    </tr>
}

我收到的错误消息是:System.Core.dll 中出现“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”类型的异常,但未在用户代码中处理

附加信息:“对象”不包含“名称”的定义

编辑:对话对象

public class Conversations
{
    public string Name { get; set; }
    public int TotalUsers { get; set; }
    public string Creator { get; set; }
    public string Status { get; set; }
    public DateTime Created { get; set; }
}

【问题讨论】:

标签: c# asp.net-mvc razor


【解决方案1】:

一个选项是使用 ViewData

在你的控制器中

ViewData["Conversations"] = lConversations 

在你看来

List<Conversations> lConversations = ViewData["Conversations"] as List<Conversations>;

【讨论】:

    【解决方案2】:

    我发现使用 ViewBag 对自己来说是不正确的方法,因为我知道我正在使用什么数据类型,因为我正在设置它们 - 我使用了一个模型。

    但是,正如上面在之前的 cmets 中提到的。将变量转换为显式类型也解决了这个问题。

    【讨论】:

      【解决方案3】:

      ViewBag,据我所知,不是强类型的——如果你知道对象的类型,你可以尝试强制转换。 (大概你会这样做,因为你的控制器填充了它)

      您也可以尝试传递强类型对象或使用 ViewModel。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 2010-10-19
        • 1970-01-01
        • 1970-01-01
        • 2011-08-05
        • 1970-01-01
        相关资源
        最近更新 更多