tags:

views:

53

answers:

2

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...

+2  A: 

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>.

tvanfosson
That won't compile. You're passing a model of type IQueryable<Anonymous type>, but the view page model parameter is a different type. You could change the query to select p;
Craig Stuntz
how do i cast a type of view page?
Vikas
@Craig -- you're right. I didn't look closely enough. I'll update my answer to select the product.
tvanfosson
@Vikas -- If you have a codebehind file -- they aren't created by default since RC1 -- you can just change the page class to inherit from ViewPage<Product>. If not, change the Inherits specification in the ASPX file to inherit from ViewPage<Product>.
tvanfosson
+2  A: 

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.

antonioh
as you suggest<%Product p = ViewData.Model%> //in case of a Strongly typed view<%Product p = (Product)ViewData.Model%> //otherwisein second second way, how can i have a type Product ? I mean is there any namespace required to import?
Vikas
if the entities are declared in a different namespace than the view, you have to import it in the view: <%@ Import Namespace="MyNamespace" %>. If it's in the same namespace you don't have to import anything
antonioh