I'm super super tired right now and probably have done a big rookie mistake. I'm doing a ViewModel to grab all my models in 1 main model class. So far I've only done News and already hitting in a error..
See error:
NullReferenceException: Object reference not set to an instance of an object. AspNetCore._Views_Home_Index_cshtml+d__21.MoveNext() in Index.cshtml + @foreach(News news in Model.Newss)
(Yes my naming is messed up but wanted to see foundation worked first).
Anyways: News.cs :
namespace UKSF.Models
{
public class News
{
public int Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public string Publisher { get; set; }
}
}
MainViewModels.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UKSF.Models
{
public class MainViewModel
{
public List<News> Newss { get; set; }
}
}
index.cshtml:
@model UKSF.Models.MainViewModel
@{
ViewData["Title"] = "Home Page";
}
@foreach(News news in Model.Newss)
{
@news.Title
}
EDIT: As you guys pointed out, the error was due of me not initializing it, I believed I had already done that in Controller page. Now its:
public IActionResult Index()
{
MainViewModel model = new MainViewModel();
model.Newss = new List<News>();
return View(model);
}