为什么ViewBag无法正确显示查询结果?

时间:2014-11-23 12:56:14

标签: asp.net-mvc entity-framework

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

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]

我在这里做错了什么?

非常感谢。

1 个答案:

答案 0 :(得分: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 => p.ID == id).First().Select(p=>p.ProjectName);之类的内容

相关问题