'do foreach with a model, Asp.NET 5

I need to do foreach but I get an error

System.NullReferenceException
HResult=0x80004003
Mensaje = Object reference not set to an instance of an object.

This is the foreach

@model UraniaWeb.Models.ViewModels.HomeVM

@foreach (var item in Model.ListaDeArticulos)
{
    <p>@item.TitleArticle</p>

in Models/ViewModels/HomeVM.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace UraniaWeb.Models.ViewModels
{
    public class HomeVM
    {
        public IEnumerable<Article> ListaDeArticulos { get ; set; }
    }
}

the key would be in the HomeController, right? I think I have to ask for the context a view to the HomeController

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using UraniaWeb.Models;

namespace UraniaWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

HomeController.cs

    using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using UraniaWeb.Models;


namespace UraniaWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Model/Article.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace UraniaWeb.Models
{
    public class Article
    {
        [Key]
        public int IdAticle { get; set; }

        [StringLength(60, MinimumLength = 3)]
        public string TitleArticle { get; set; }
        public string DescritionArticle { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Fecha de Alta")]
        public DateTime DateCreation { get; set; }
        [DisplayFormat(NullDisplayText = "")]

        [DataType(DataType.Upload)]
        public string UrlImagen1 { get; set; }
        [DisplayFormat(NullDisplayText = "")]
        public string UrlImagen2 { get; set; }
        [DisplayFormat(NullDisplayText = "")]
        public string UrlSound1 { get; set; }
    }

}

I only want to put the data of the articles in the home page, then I will give it a card shape with bootstrap

articlesController.cs

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UraniaWeb.Models;
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace UraniaWeb.Controllers
{
    public class ArticlesController : Controller
    {
        private readonly UraniaWebDbContext _context;

        private readonly IWebHostEnvironment _hostingEnvironment;


        public ArticlesController(UraniaWebDbContext context, IWebHostEnvironment hostEnvironment)
        {
            _context = context;
            _hostingEnvironment = hostEnvironment;
        }

        // GET: Articles
        public async Task<IActionResult> Index()
        {
            return View(await _context.Articles.ToListAsync());
        }

        // GET: Articles/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var article = await _context.Articles
                .FirstOrDefaultAsync(m => m.IdAticle == id);
            if (article == null)
            {
                return NotFound();
            }

            return View(article);
        }

        // GET: Articles/Create
        public IActionResult Create()
        {
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(int id, [Bind("IdAticle,TitleArticle,DescritionArticle,DateCreation,UrlImagen1,UrlImagen2,UrlSound1")]  Article articulo, DateTime dateTime)
        {
            if (ModelState.IsValid)
            {
                string primaryPath = _hostingEnvironment.WebRootPath;
                var file = HttpContext.Request.Form.Files;
                if (articulo.article.IdAticle != 0)
                {
                    string nameFile = Guid.NewGuid().ToString();
                    var subidas = Path.Combine(primaryPath, @"imagenes\articulos");
                    var extension = Path.GetExtension(file[0].FileName);
                    

                    using (var fileStream = new FileStream(Path.Combine(subidas, nameFile + extension), FileMode.Create))
                    {
                        file[0].CopyTo(fileStream); 
                    }
                    articulo.article.UrlImagen1 = @"\imagenes\articulos\" + primaryPath + extension;
                    

                    _context.Articles.Add(articulo.article);
                    _context.SaveChanges();
                }

                articulo.DateCreation = DateTime.Now;
                _context.Add(articulo);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(articulo);
        }

        // GET: Articles/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var article = await _context.Articles.FindAsync(id);
            if (article == null)
            {
                return NotFound();
            }
            return View(article);
        }

        
        [HttpPost]
        [ValidateAntiForgeryToken]
        
        public async Task<IActionResult> Edit(int id, [Bind("IdAticle,TitleArticle,DescritionArticle,DateCreation,UrlImagen1,UrlImagen2,UrlSound1")] Article article)
        {
            if (id != article.IdAticle)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(article);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ArticleExists(article.IdAticle))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(article);
        }

        // GET: Articles/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var article = await _context.Articles
                .FirstOrDefaultAsync(m => m.IdAticle == id);
            if (article == null)
            {
                return NotFound();
            }

            return View(article);
        }

        // POST: Articles/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var article = await _context.Articles.FindAsync(id);
            _context.Articles.Remove(article);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ArticleExists(int id)
        {
            return _context.Articles.Any(e => e.IdAticle == id);
        }
    }
}



Solution 1:[1]

You have not initialize ListaDeArticulos before looping it. You need to initialize it in your controller or you can do this public IEnumerable<Article> ListaDeArticulos { get ; set; } = new List<Article> to initialize it once it is declared, but it wont have any element inside the IEnumerable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Loong