【问题标题】:Why is ViewBag not displaying query result correctly?为什么 ViewBag 不能正确显示查询结果?
【发布时间】:2014-11-23 12:56:13
【问题描述】:

我的控制器中有以下内容:

public ActionResult Index(int? id)
    {
        int projectId = (int)id;

        //Get the project name to use in the view
        var projName = from p in db.Projects where p.ID == id select p.ProjectName;
        ViewBag.projectName = projName.ToString();

//Rest of code ommitted

在我看来:

<p>There are no actors for the @ViewBag.projectName yet.</p>

问题是,我的视图正在呈现以下内容,而不是我的项目名称:

SELECT [Extent1].[ProjectName] AS [ProjectName] FROM [dbo].[Project] AS [Extent1] WHERE [Extent1].[ID] = @p__linq__0 还没有演员。

我已尝试根据此问题 Passing query results in a viewbag 将代码更改为 ViewBag.projectName = projecName.ToList();,但结果如下:

There are no actors for the System.Collections.Generic.List1[System.String] 还没有。

我在这里做错了什么?

帮助非常感谢。

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    projName 目前只是一个 IQueryable 对象,就像您现在拥有的一样。

    您需要实际执行对 db 的查询并将结果保存在 ViewBag.projectName 属性中。

    将您的 var projName = from p in db.Projects where p.ID == id select p.ProjectName; 行切换为以下内容应该可以解决此问题:

        var projName = db.Projects.Find(id).ProjectName;
    

    (假设 IDprojects 的主键 - 如果不是,请改用 db.Projects.Where(p =&gt; p.ID == id).First().Select(p=&gt;p.ProjectName); 之类的东西)

    【讨论】:

    • 成功了,谢谢 :-) 你救了我的星期天。按照您的建议切换线路意味着我可以使用ViewBag.projectName = projName;。 (以防万一其他人在将来遇到类似问题时阅读此内容)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    相关资源
    最近更新 更多