使用模型执行 foreach,Asp.NET 5

do foreach with a model, Asp.NET 5

提问人:Gastón Angúlo Alcácer 提问时间:4/21/2022 最后编辑:Gastón Angúlo Alcácer 更新时间:4/28/2022 访问量:129

问:

我需要执行foreach,但是出现错误

System.NullReferenceException
HResult=0x80004003
Mensaje = 对象引用未设置为对象的实例。

这是 foreach

@model UraniaWeb.Models.ViewModels.HomeVM

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

在模型/视图模型/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; }
    }
}

密钥将在 HomeController 中,对吧?我想我必须问上下文 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();
        }

首页控制器.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 });
        }
    }
}

模型/文章.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; }
    }

}

我只想把文章的数据放在首页,然后我会用bootstrap给它一个卡片形状

文章控制器 .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);
        }
    }
}

asp.net 模型 NullReferenceException

评论


答:

0赞 Loong 4/21/2022 #1

在循环之前尚未初始化。您需要在控制器中初始化它,或者您可以在声明后执行此操作来初始化它,但它内部不会有任何元素。ListaDeArticulospublic IEnumerable<Article> ListaDeArticulos { get ; set; } = new List<Article>IEnumerable

评论

0赞 Gastón Angúlo Alcácer 4/21/2022
这个想法是它从数据库中获取值,在 ArticulosController 中.cs我有... // GET: articles public async Task<IActionResult> Index() { return View(await _context.Articles.ToListAsync());} 我应该在控制器中定义,当执行“get”时,它采用基数的值,执行 return View() 对吗?
0赞 Gastón Angúlo Alcácer 4/21/2022
或者如何将值引入 IEnumerable???
0赞 Loong 4/22/2022
请编辑问题并将您的代码发布在控制器中,以便我们了解其中发生的情况
0赞 Gastón Angúlo Alcácer 4/22/2022
我在那里上传了代码
0赞 Loong 4/25/2022
我仍然找不到返回模型的代码,请发布 ArticulosController.cs