user4103496
user4103496

Reputation:

How to pass a string from LINQ query to ViewBag

I am trying to dynamically generate a title for my page. I'm using this query to select an item type:

ViewBag.itemType = From row In db.tblCategories
                   Where row.Item_Type_Identifier = itemType
                   Select CStr(row.Item_Type)
                   Distinct

And in my view I'm trying to display it like so:

<h2>Details for @ViewBag.itemType </h2>

Instead of my view displaying the value retrieved from the query I am seeing the LINQ query actually being displayed like so:

SELECT [Distinct1].[Item_Type] AS [Item_Type] 
FROM ( SELECT DISTINCT [Extent1].[Item_Type] 
AS [Item_Type] FROM [dbo].[tblCategories] AS [Extent1] 
WHERE [Extent1].[Item_Type_Identifier] = @p__linq__0 ) 
AS [Distinct1]  

I've attempted to place the value from the query in a variable, and then add that variable to ViewData and then retrieve that value in the view.

I've attempted to use .ToString on my LINQ instead of casting CStr.

Why is my query being placed in my ViewBag instead of the value my LINQ returns?

Upvotes: 0

Views: 1199

Answers (1)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

It is because you pass the LINQ query (i.e. IQueriable in this case).

Try something like this:

ViewBag.itemType = (From row In db.tblCategories
                   Where row.Item_Type_Identifier = itemType
                   Select CStr(row.Item_Type)
                   Distinct).Single()

(in case if this syntax allowed in VB.NET)

Upvotes: 3

Related Questions