如何将 MVC 控制器中 select 语句的值发送到 Viewbag
How to send a value from a select statement in MVC controller to Viewbag
我想 return 使用下面的 LINQ 查询只是一个 ViewBag 的值
var myCompanyName = (from c in db.Companies
where c.CompanyId == CompanyID
select c.CompanyName).ToString();
ViewBag.myCompanyName = myCompanyName;
在我的 MVC 控制器中,但在我的视图中得到以下输出。
SELECT [Extent1].[CompanyName] AS [CompanyName] FROM [dbo].[Companies] AS [Extent1] WHERE [Extent1].[CompanyId] = @p__linq__0 Company Name from Controller Action
视图包中预期的结果 ViewBag 应该类似于:CompanyName XYZ。请问我该怎么做才正确?
您没有具体化您的查询,我怀疑您想要 return 单个值(而不是 IEnumerable<string>
),因此您需要将 .ToString()
替换为 .FirstOrDefault()
var myCompanyName = (from c in db.Companies
where c.CompanyId == CompanyID
select c.CompanyName).FirstOrDefault();
ViewBag.myCompanyName = myCompanyName;
或者如果您确实想要 string
的集合,那么它将是 .ToList()
我想 return 使用下面的 LINQ 查询只是一个 ViewBag 的值
var myCompanyName = (from c in db.Companies
where c.CompanyId == CompanyID
select c.CompanyName).ToString();
ViewBag.myCompanyName = myCompanyName;
在我的 MVC 控制器中,但在我的视图中得到以下输出。
SELECT [Extent1].[CompanyName] AS [CompanyName] FROM [dbo].[Companies] AS [Extent1] WHERE [Extent1].[CompanyId] = @p__linq__0 Company Name from Controller Action
视图包中预期的结果 ViewBag 应该类似于:CompanyName XYZ。请问我该怎么做才正确?
您没有具体化您的查询,我怀疑您想要 return 单个值(而不是 IEnumerable<string>
),因此您需要将 .ToString()
替换为 .FirstOrDefault()
var myCompanyName = (from c in db.Companies
where c.CompanyId == CompanyID
select c.CompanyName).FirstOrDefault();
ViewBag.myCompanyName = myCompanyName;
或者如果您确实想要 string
的集合,那么它将是 .ToList()