I have a similar situation as this guy. I also wish to put a @model IEnumerable<>
inside the parent which is a normal @model.
I did the whole thing with the view model combining the two. But now I don't know how to proceed when I wish to implement my webgrid. How should I bind the model to the webgrid, and should I use @foreach
since I technically don't have an IEnumerable
model but I do have a IEnumerable
property of that model?
@model MyViewModel
@{
var myWebGrid = new WebGrid(Model.theIEnumarablePropertyOfMyViewModel);
}
@foreach (var item in Model.theIEnumarablePropertyOfMyViewModel)
{
@myWebGrid.GetHtml()
}
Take a look at this article for a good basic explanation of using a WebGrid.
The most important parts that correspond to the code you posted (without the nested IEnumerable):
public ActionResult List()
{
IEnumerable<Product> model =
_productService.GetProducts();
return View(model);
}
@model IEnumerable<MsdnMvcWebGrid.Domain.Product>
@{
ViewBag.Title = "Basic Web Grid";
}
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml()
So everything looks fine in your setup, including the nested IEnumerable, except the line that states:
@foreach (var item in Model.theIEnumarablePropertyOfMyViewModel){
@myWebGrid.GetHtml()
}
You don't need to iterate over the collection again! You already give the collection in the constructor of the WebGrid
and afterwards you just call it's GetHtml()
method to render the results. So the above simply becomes:
@myWebGrid.GetHtml()