0
What I looked for, we used viewmodel to then access in the view several models, my problem is that I have an error that does not allow me to access the Model. And everywhere I look, I can’t figure out where I’m going wrong. Viewmodel:
public class ViewModel
{
public List<Category> Categories { get; set; } = new List<Category>();
public List<Ad> Ads { get; set; } = new List<Ad>();
}
Controller:
public class ViewModelController : Controller
{
private LivrinhosContext db = new LivrinhosContext();
// GET: ViewModel
public ActionResult Index()
{
ViewModel mymodel = new ViewModel();
mymodel.Categories = db.Categories.ToList(); //Get all categories
mymodel.Ads = db.Ads.Take(1).OrderByDescending(x => x.BookID).ToList(); //get last ad
return View(mymodel);
}
}
The view:
@model IEnumerable<LivrinhosMVC.DAL.ViewModel>
@{
ViewBag.Title = "Home Page";
}
<div class="container">
<div class="row" style="margin:2em 0">
<div class="col-sm-4">
@Html.Label("Categorias")
<table class="table-condensed">
@foreach (var category in Model.Categories) {
<tr>
<td>@Html.ActionLink(category.Name, "../Category/Books", new { id = category.ID }, null)</td>
</tr>
}
</table>
</div>
<div class="col-sm-8" style="display:inline">
@Html.TextBox("BookTitle", null, new { placeholder = "Título...", @class = "form-control" })
@Html.DropDownList("Cities", "Portugal")
@Html.ActionLink("Pesquisar", "Books", null, null, new { @class = "btn btn-primary" })
</div>
<div class="row">
@foreach (var ad in Model.Ads)
{
<div class="col-sm-3">
@Html.Label(ad.Title)
</div>
}
</div>
</div>
</div>
You are returning a Viewmodel to a view that expects Ienumerable<Viewmodel>.
– George Wurthmann
Which error?
– Lodi