Reputation: 3
Im tring to make a custom viewmodel class which takes 2 model list or enumerable. when I try to show in a view class it gives me following error.
The model item passed into the dictionary is of type ""Prototype01.ViewModels.StockViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IList`1[Prototype01.ViewModels.StockViewModel]""
I have tried making seperate views and used simple models to project in a view. it works fine but when i try to get viewmodel it does not works as i expect.
public class StockController : Controller
{
private ApplicationDbContext _context;
public StockController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
// GET: Stock
public ActionResult StockIndex()
{
var batteries = _context.Batteries.ToList();
var rims = _context.Rims.ToList();
var viewmodel = new StockViewModel
{
Batteries = batteries,
Rims = rims
};
return View(viewmodel);
}
}
public class StockViewModel
{
public IEnumerable<Battery> Batteries { get; set; }
public IEnumerable<Rim> Rims { get; set; }
}
@model IEnumerable<Prototype01.ViewModels.StockViewModel>
@{
ViewBag.Title = "StockIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Stock Management</h2>
@if (!Model.Any())
{
<p>We don't have any Batteries yet.</p>
<label class="btn-group">@Html.ActionLink("Add New", "New", "Battery")
</label>
}
else
{
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>battery ID</th>
<th>battery Name</th>
</tr>
</thead>
<tbody>
@foreach (var bt in Model)
{
<tr>
<td> tying to show batteries here</td>
</tr>
}
</tbody>
</table>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Rim ID</th>
<th>Rim Name</th>
</tr>
</thead>
<tbody>
@foreach (var rm in Model)
{
<tr>
<td> tying to show Rims here</td>
</tr>
}
</tbody>
</table>
}
I am trying to store data in controller method and send viewmodel to just show 2 tables with Id and name from database table Batteries and Rims
on the other hand, I am getting an exception The model item passed into the dictionary is of type 'Prototype01.ViewModels.StockViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Prototype01.ViewModels.StockViewModel]'.
Upvotes: 0
Views: 34
Reputation: 1556
You are iterating over the Model, rather than over individual enumerators; Batteries and Rims in your ViewModel.
So change the line:
@foreach (var bt in Model)
To:
@foreach (var bt in Model.Batteries)
And the same for you rims:
@foreach (var rm in Model)
To:
@foreach (var rm in Model.Rims)
Also change:
@model IEnumerable<Prototype01.ViewModels.StockViewModel>
to:
@model Prototype01.ViewModels.StockViewModel
Upvotes: 0