我有一个MVC 5项目,接下来的两个类作为模型:
public class Verbruik
{
public string Gemiddelde1 { get; set; }
public string Gemiddelde2 { get; set; }
public List<VerbruikRow> verbruikList = new List<VerbruikRow>();
}
public class VerbruikRow
{
public string Datum { get; set; }
public string Liter { get; set; }
public string Km { get; set; }
public string Verschil { get; set; }
}
以下是我拥有的控制器的代码:
// GET: Verbruik
public ActionResult Index()
{
Verbruik model = new Verbruik();
VerbruikRow rowtest = new VerbruikRow();
rowtest.Datum = "1/1/2015";
rowtest.Km = "2000";
rowtest.Liter = "0";
rowtest.Verschil = "0";
model.verbruikList.Add(rowtest);
model.Gemiddelde1 = "";
model.Gemiddelde2 = "";
return View();
}
这是视图的代码:
@model EfenkaMobile.Models.Verbruik
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="row">
<div class="col-md-10">
<h3>
@Html.DisplayFor(m => m.Gemiddelde1)
</h3>
<h3>@Html.DisplayFor(m => m.Gemiddelde1)</h3>
</div>
</div>
<div class="row">
<div class="col-md-10">
<h3>
@Html.DisplayFor(m => m.Gemiddelde2)
</h3>
<h3>@Html.DisplayFor(m => m.Gemiddelde2)</h3>
</div>
</div>
</br >
@foreach (var x in Model.verbruikList)
{<li>@x.Datum</li>
<li>@x.Km</li>
<li>@x.Liter</li>
<li>@x.Verschil</li>}
这是现在的所有测试代码,但最终我将从数据库中获取数据并使用它来填充verbruiklist中的数据行。然后我想在视图中显示这个数据,并带有一个分页块。
当我尝试运行它时,当我到达razor foreach循环时出现错误。
这是我尝试运行时遇到的错误:
An exception of type 'System.NullReferenceException' occurred in App_Web_2rvwlpox.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
答案 0 :(得分:2)
您必须将模型返回到视图:
public ActionResult Index()
{
Verbruik model = new Verbruik();
VerbruikRow rowtest = new VerbruikRow();
rowtest.Datum = "1/1/2015";
rowtest.Km = "2000";
rowtest.Liter = "0";
rowtest.Verschil = "0";
model.verbruikList.Add(rowtest);
model.Gemiddelde1 = "";
model.Gemiddelde2 = "";
return View(model);
}
因为你的观点需要它:
@model EfenkaMobile.Models.Verbruik