Carlo
Carlo

Reputation: 107

View data from another controller in ASP.NET Core MVC

I'm trying to build an ASP.NET Core 6 MVC app.

I have two controllers 'home' and 'work'. How can I display data from 'work' model in the home/index view?

Unfortunately, I don't know the terminology to better formulate the question, but actually I want to achieve that on the home page I can display the last few works.

The part where I enter/edit data works fine. When I go to the /Works/Index page, I see all the entered data. How to display, for example, the last 4 on the home page of the application

In index.cshtml I have

@model IEnumerable<Website.Models.Work>                
@foreach (var item in Model)
{
    <div class="col-lg-3 col-sm-6">
        <div class="gallery-item wow fadeInUp delay-0-2s">
            <img src="~/assets/images/gallery/gallery-1.jpg" alt="Gallery">
                <div class="gallery-content">
                    <span class="category"><a href="portfolio-details.html">@Html.DisplayFor(modelItem => item.Tag)</a></span>
                    <h5><a href="portfolio-details.html">@Html.DisplayFor(modelItem => item.Headline)</a></h5>
                </div>
       </div>
   </div>
}

But I get an error:

System.NullReferenceException: Object reference not set to an instance of an object.

Upvotes: 1

Views: 569

Answers (1)

Rena
Rena

Reputation: 36705

If you just want to know how to display the data on page, here is a working demo below:

HomeController

public class HomeController: Controller
{

    private readonly YourDbContext _context;        
    public HomeController(YourDbContext context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
       //get the last 4 records...
        var model = _context.Work.AsEnumerable().Reverse().Take(4).ToList();
        return View(model);            
    }
}

Home/Index.cshtml

@model IEnumerable<Website.Models.Work>                
@foreach (var item in Model)
{
    <div class="col-lg-3 col-sm-6">
        <div class="gallery-item wow fadeInUp delay-0-2s">
            <img src="~/assets/images/gallery/gallery-1.jpg" alt="Gallery">
                <div class="gallery-content">
                    <span class="category"><a href="portfolio-details.html">@Html.DisplayFor(modelItem => item.Tag)</a></span>
                    <h5><a href="portfolio-details.html">@Html.DisplayFor(modelItem => item.Headline)</a></h5>
                </div>
       </div>
   </div>
}

Upvotes: 2

Related Questions