NullReferenceException:通过控制器访问 ViewModel 列表时,对象引用未设置为对象的实例

NullReferenceException: Object reference not set to an instance of an object When accessing ViewModel list through controller

所以我的视图模型没有正确地将 CSV 文件的信息提供给视图。我已经放置了一个断点并且列表 "Stocks" 很好地填满了我什至可以看到 public IEnumerable<Stock> Stocks { get; set; } 中的所有值但是当我到达我的控制器时 var, ViewModel 是空的?有什么建议么? 这是视图模型

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StockApp.Models;
using System.Windows;
using System.IO;
using System.Text;
using CsvHelper;
using Microsoft.VisualBasic;


namespace StockApp.ViewModels.StockInfo
{
    public class StockInfoViewModel
    {
        public StockInfoViewModel()
        {
            List<Stock> Stocks = new List<Stock>();

            string file ="../StockApp/App_Data/companylist.csv";
            using(var reader = new StreamReader(file))
            {


                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    var values = line.Split(',');
                    Stocks.Add(new Stock { Name = values[1], Symbol = values[0] });
                }
            }

        }
        public IEnumerable<Stock> Stocks { get; set; }

    }
}

这是控制器

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StockApp.Models;
using System.Windows;
using System.IO;
using System.Text;
using CsvHelper;
using Microsoft.VisualBasic;

namespace StockApp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult StockInfo()
        {
            var ViewModel = new ViewModels.StockInfo.StockInfoViewModel().Stocks;

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

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


        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            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 });
        }
    }
}

模特

using System;
using System.Collections.Generic;

namespace StockApp.Models
{
    public class StockNamesModel
    {
        public List<Stock> Stocks {get; set;}

    }

    public class Stock 
    {
        public string Symbol{get; set;}
        public string Name {get; set;}
    }


}

最后但并非最不重要的剃刀代码

@model StockApp.ViewModels.StockInfo.StockInfoViewModel
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<h1>Our Advanced Algorithims To Buy and Sell These Stocks</h1>

<table class="table table-dark">
    <thead>
        <tr>
            <th scope="col">Symbol</th>
            <th scope="col">Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var stock in Model.Stocks)
        {
            <tr>
                <td>@stock.Symbol</td>
                <td>@stock.Name</td>
            </tr>
        }

    </tbody>
</table>

如有帮助,将不胜感激!

StockInfoViewModel 实例的 Stocks 属性 未分配。您在构造函数中设置了意图变量 Stocks

您需要更换线路

List<Stock> Stocks = new List<Stock>();

this.Stocks = new List<Stock>();

您只需更改 ViewModel

中的 2 项内容

ViewModel

  • 去掉List<Stock>直接赋值,看起来像Stocks = new List<Stock>();
  • IEnumerable<Stock>List<Stock> 变成 public List<Stock> Stocks { get; set; }


null 的原因:

List<Stock> Stocks 范围在构造函数内并且 IEnumerable<Stocks> 未跟踪 List<Stock> Stocks

并且您正在尝试从您的控制器访问 IEnumerable,它首先没有分配任何东西

更新代码:

public class StockInfoViewModel
{
    public StockInfoViewModel()
    {
        Stocks = new List<Stock>();

        string file ="../StockApp/App_Data/companylist.csv";
        using(var reader = new StreamReader(file))
        {


            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');
                Stocks.Add(new Stock { Name = values[1], Symbol = values[0] });
            }
        }

    }
    public List<Stock> Stocks { get; set; }

}
}