Introduction: In some cases we need to display data in form of parent child i.e. Order and product scenario for shopping cart web site.I have used Web Grid to display records for my asp net MVC 3 application.
Model classes: I have created two model classes Order and Product
public class Order
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public List<Product> ProductList { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult NestedGrid()
{
var Orders = new List<Order>();
var products1 = new List<Product>();
products1.Add(new Product { ProductId = 1, Name = "laptop" });
products1.Add(new Product { ProductId = 5, Name = "pen drive" });
Orders.Add(new Order { OrderId = 1, ProductList = products1, OrderDate = DateTime.Now });
var products2 = new List<Product>();
products2.Add(new Product { ProductId = 3, Name = "Hard disk" });
products2.Add(new Product { ProductId = 4, Name = "Mouse" });
Orders.Add(new Order { OrderId = 2, ProductList = products2, OrderDate = DateTime.Now });
return View(Orders);
}
}
View: I have used Razor view engine.
@model IEnumerable<MvcApplication1.Data.Order>
@{
ViewBag.Title = "NestedGrid";
}
@{
WebGrid topGrid = new WebGrid(source: Model);
}
<h2>NestedGrid</h2>
<div id="grid">
@topGrid.GetHtml(columns:
topGrid.Columns(
topGrid.Column("OrderId"),
topGrid.Column("ProductList", format: (item) =>
{
WebGrid subGrid = new WebGrid(item.ProductList);
return subGrid.GetHtml(
columns: subGrid.Columns(
subGrid.Column("ProductId"),
subGrid.Column("Name")
)
);
})
,topGrid.Column("OrderDate")
)
)
</div>
Result:
Conclusion: So we can easily create nested grid with the help of WebGrid in asp.net MVC 3 application.Hope this will be useful to you.
Thanks
Rajendra