Vikas
Vikas

Reputation: 24332

how do i display query result in view?

I am using MVC RC2.

I have Two tables 1)Product (PID, PName, CIDfk); 2)Category(CID, CName);

So i query like these

var Product = from p in dc.Product
                       from C in dc.Category
                       where p.CIDfk == c.CID
                       select new { ProductName = p.PName, ProductCategory = c.CName };
return view();

where dc is database context of LINQ-to-SQL class (.dbml);

How do i display in view? where i pass Product? (in viewdata or in 'return view()')

Please help me out...

Upvotes: 1

Views: 2552

Answers (2)

tvanfosson
tvanfosson

Reputation: 532695

You want to have a strongly typed view and pass the product as the view model

 var product = from p in dc.Product
                   from C in dc.Category
                   where p.CIDfk == c.CID
                   select p;

 return View( product );

where your view is of type ViewPage<Product>.

Upvotes: 2

antonioh
antonioh

Reputation: 2944

You can both use:

- ViewData["MyName"] = product.SingleOrDefault(); 

This way from the view you'd do:

 <% Product p = (Product)ViewData(p) %>

or populate the model:

ViewData.Model = product.SingleOrDefault();

This way from the view you'd do:

<%Product p = ViewData.Model%> //in case of a Strongly typed view
<%Product p = (Product)ViewData.Model%> //otherwise

After populating either ViewData or the Model you can call:

return View();

Another approach is calling the View overload that accepts the model as parameter, as tvanfosson said.

Upvotes: 2

Related Questions