I am completely new to ASP.NET Core and following along the Microsoft's documentation and developing a simple web application. Sorry, if the question is not clear.
I have created a model, view and controller called Broadcast
. This model has a field called live. I would like to access this model to home view's index.cshtml
file which is a separate view.
I have tried including Broadcast
view on the top at index.cshtml
file home view
@model IEnumerable<SideCar.Models.Broadcast>
When I am accessing the model using @foreach
I get the following error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Could you please guide, what should I learn to access the model into a different view? Thank you.
Here is the controller:
using Microsoft.AspNetCore.Mvc;
using SideCar.Data;
using SideCar.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SideCar.Controllers
{
public class BroadcastController : Controller
{
private readonly ApplicationDbContext _db;
public BroadcastController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Broadcast> objList = _db.Boradcast;
return View(objList);
}
}
}
and model:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace SideCar.Models
{
public class Broadcast
{
[Key]
public int Id { get; set; }
public string BroadcastHeading { get; set; }
public string BroadcastDesc1 { get; set; }
public string BroadcastDesc2 { get; set; }
public DateTime ActiveDate { get; set; }
public DateTime ExpiryDate { get; set; }
public string Live { get; set; }
}
}
question from:
https://stackoverflow.com/questions/65646996/how-to-access-a-model-to-home-view-index-cshtml-file-in-asp-net-core-5-mvc 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…