How do I view the parent view model MVC3 C#?

倖福魔咒の 提交于 2019-12-06 08:57:45

You need to adapt your view model:

public class DishBlogg
{
    public IEnumerable<Blogg> Blogging { get; set; }
    public IEnumerable<Dish> Dishing { get; set; }
}

and then try adding a .ToList() call to eagerly execute the queries in the controller:

public ActionResult Index()
{
    var model = new DishBlogg
    {
        Blogging = db.Bloggs.OrderByDescending(o => o.ID).Take(1).ToList(),
        Dishing = db.Dishes.OrderByDescending(o => o.ID).Take(1).ToList(),
    }
    return View(model);
}

and then in your view:

@model XXXXXX.Models.DishBlogg

@foreach (var blog in Model.Blogging)
{
    ...
}

@foreach (var blog in Model.Dishing)
{
    ...
}

I think your problem is rather clear.

Your model is a DishBlog but you are passing a Blogg

Try this:

public ActionResult Index()
        {

            var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1).FirstOrDefault();
            var list = new List<DishBlogg>();
            list.Add(new DishBlogg(){Blog = lastblog});

            return View(list);
        }

if you want to pass the viewmodel "DishBlogg" to your view , you need to remove the IEnumerable from the model declaration in your view

In your view you are using @model IEnumerable<XXXXXX.Models.DishBlogg> which indicates that the model expected by the View is of type IEnumerable of DishBlogg.

However in the controller you are passing an object of type DishBlogg as a model return View(viewModel); hence the error.

Either change the view to have @model XXXXXX.Models.DishBlogg

or change your view model to return a list and pass a IEnumerable of DishBlogg as model to the view in controller

so instead of this @model IEnumerable<XXXXXX.Models.DishBlogg>
use this @model <XXXXXX.Models.DishBlogg>

change your viewmodel class to this

public class DishBlogg(Blogg blogg, Dish dish)
{
    this.LastBlogg = blogg;
    this.LastDish = dish;
}
public Blogg LastBlogg { get; private set; }
public Dish LastDish { get; private set; }


Fill and pass the view model to your view

public ActionResult Index()
{
    var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1);
    var lastdish = db.Bloggs.OrderByDescending(o => o.ID).Take(1);
    var viewModel = new DishBlogg(lastblogg , lastdish );

    return View("Index", viewModel);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!