开发者

How can I show two ActionResult in Home/index view MVC C#

I have two controllers

BloggsController:

   //Last blogg from the database
        public ActionResult LastBlogg()
        {
            var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1);

            return View(lastblogg);
        }

DishesController:

/开发者_StackOverflow社区/Last recipe from the database
public ActionResult LastRecipe()
{
    var last = db.Dishes.OrderByDescending(o => o.ID).Take(1);

    return View(last);
}

I want to show the result of this on my start-page, Views/Home/index.

If I put this in my HomeController:

//Last recipe from the database
public ActionResult Index()
{
    var last = db.Dishes.OrderByDescending(o => o.ID).Take(1);

    return View(last);
}

Can I show the result in of recipe on my start-page but how do I show both the result of the blogg and recipe on om startpage?


You should create separate partial views for LastBlogg and LastRecipe and place both of them to your home page (new Model will be required).


Create a View Model and add both Blogg and Recipe to it.

public ActionResult Index()
{
    var lastRecipe = db.Dishes.OrderByDescending(o => o.ID).Take(1);
    var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1);

   var model = new BloggRecipeModel(lastRecipe, lastblogg);

   return View(model);

}


You could simply create a custom ViewData in your Models folder, like this:

public class MyCustomViewData
{
public Dish Dish {get;set;}
public Blog Blog {get;set;}
}

Then in your controller:

ViewData.Model = new MyCustomViewData
{
Dish = db.Dishes.OrderByDescending(o => o.ID).Take(1);
Blog = db.Bloggs.OrderByDescending(o => o.ID).Take(1);
}

return View();

And in your view, set the @Model property to Models.MyCustomViewData and handle it accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜