Reputation: 2663
I have an array of items in my view and am trying to iterate over that array and pass each item to a partial view, however it throws an exception saying that I'm trying to pass the entire array rather than just the single item to the partial view.
My main view:
@model Product[]
@foreach (var item in Model)
{
@Html.Partial("_ProductDetail", item)
}
My partial view:
@model Product
<div>
@Model.Description
</div>
The exception message:
The model item passed into the dictionary is of type 'Product[]', but this dictionary requires a model item of type 'Product'.
What am I doing wrong?
Edit The controller is definitely passing an array, here's the code though:
public ActionResult Category(string id)
{
var model = FakeDb.Products;
return View(model);
}
And the FakeDb:
public static class FakeDb
{
public static Product[] Products { get; set; }
static FakeDb()
{
Products = new Product[2];
DateTime utcNow = DateTime.UtcNow;
ProductPic pp1 = new ProductPic { Filename = "71b.jpg", Default = true };
Product p1 = new Product { DateAdded = utcNow, Price = 395, Quantity = 1, Pics = new List<ProductPic> { pp1 }, Description = "5 ft. x 8 ft. Blue, Yellow" };
Products[0] = p1;
ProductPic pp2 = new ProductPic { Filename = "72b.jpg" };
Product p2 = new Product { DateAdded = utcNow.AddDays(-1), Quantity = 2, Pics = new List<ProductPic> { pp2 }, Description = "5 ft. x 8 ft. Blue, Green" };
}
}
Upvotes: 2
Views: 2503
Reputation: 3082
When an element passed to Partial
is null, it will pass parent view Model
instead. So if element in Product[]
array is null, parent's view model will be passed to Partial
.
You could possibly check if any element in array you're iterating over is not null
or pass @Html.Partial("_ProductDetail", new ViewDataDictionary(item))
.
Foreach approach:
@model Product[]
@foreach (var item in Model)
{
if (item != null)
{
@Html.Partial("_ProductDetail", item)
}
}
ViewDataDictionary approach:
@Html.Partial("_ProductDetail", new ViewDataDictionary(item))
Upvotes: 4