Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

How to access a model to home view index.cshtml file in ASP.NET Core 5 MVC?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change you index action to this:

public IActionResult Index()
        {
            var objList = _db.Set<Broadcast>().ToArray();
            return View(objList);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...