I have Error in viewModel ASP.NET MVC C#

Asked

Viewed 130 times

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>.

  • Which error?

2 answers

1

The problem is you’re returning a ViewModel for your view that actually expects to receive a IEnumerable<ViewModel>.

Review the model of his view. Correct for her to receive the value returned in ViewModelController is:

@model LivrinhosMVC.DAL.ViewModel

Otherwise you need to review your Viewmodel and your Controller to make a type upload IEnumerable<ViewModel>.

0

Why not create the viewModel with whole object of Category and Ad

public class ViewModel
{
    public Category Categories  { get; set; }
    public Ad Ads  { get; set; }
}
  • Your answer makes sense, but doing so it needs to also change the controller.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.