I have a table with products details and i want to group it by supplierId and pass the query result to a MVC view which throws error " The model item passed into the dictionary is of type 'System.Collections.Generic.List`1<>f__AnonymousType`2[System.Int32,System.Linq.IGrouping`2, but this dictionary requires a model item of type"
My table is:
ProductDetails
ProductId
SKU
SupplierId
Package
Price
I want to group it according to the supplier. Pls help me in how to pass the LINQ grouped query result to a MVC view. and how to display the recrds in groups in the View.
TIA.
Loading
Jignesh TrivediPosted May 20, 2014, 1:29 AM
hi,
Try
custom Models required....
public class ProductDetail ProductDetails { get; set; }
{
public int ProductId { get; set; }
public string SKU { get; set; }
public int SupplierId { get; set; }
public string Package { get; set; }
public double Price { get; set; }
}
public class RenderView
{
public int SupplierId { get; set; }
public IEnumerable
}
// Controller Action method
public ActionResult Index() l = new List();
{
List
l.Add(new ProductDetail { ProductId = 1, SKU = "test1", SupplierId = 1, Package = "", Price = 25 });
l.Add(new ProductDetail { ProductId = 2, SKU = "test2", SupplierId = 1, Package = "", Price = 30 });
l.Add(new ProductDetail { ProductId = 3, SKU = "test3", SupplierId = 2, Package = "", Price = 35 });
l.Add(new ProductDetail { ProductId = 4, SKU = "test4", SupplierId = 2, Package = "", Price = 55 });
ViewBag.Message = "Welcome to ASP.NET MVC!";
var model = from p in l
group p by p.SupplierId into g
select new RenderView { SupplierId = g.Key, ProductDetails = g.ToList() };
return View(model);
}
//View
@model IEnumerable
@{
ViewBag.Title = "Home Page";
}
@ViewBag.Message
To learn more about ASP.NET MVC visit http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc.
@{
foreach(var f in Model)
{
SupplierId : @f.SupplierId
foreach(var k in f.ProductDetails)
{
@k.ProductId
}
}
}
hope this will help you.
Anupam SinghPosted May 20, 2014, 1:11 AM
We use group by in sql for grouping the records with aggregate function.
Same works in linq to sql.
here you mentioned you want to group records by supplierId ?
but with what. anyway let me assume you want to group by with price.
now your linq query will look like this:
its not tested .please verify before use.