我已经向视图模型添加了一个列表,但是当我在视图的foreach循环中访问它时,它会抛出:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_MyActivationCampaign_Campaign.ExecuteAsync() in Campaign.cshtml
+ foreach(var dp in Model.DpRestrictedList)
这是我添加的列表:
public List<DpRestricted> DpRestrictedList { get; set; } = new List<DpRestricted>()
{
new DpRestricted(){DpId = 1, Name = "Post Restricted" },
new DpRestricted(){DpId = 2, Name = "Unrestricted" },
new DpRestricted(){DpId = 3, Name = "Customer Restricted" }
};
}
public class DpRestricted
{
public int DpId { get; set; }
public string Name { get; set; }
}
我正试图像这样遍历它:
<div class="row">
<fieldset>
<legend>Delivery Methods</legend>
<div id="radio">
@*<input type="radio" id="new-method">
<label for="new-method">New Method</label>
<input type="radio" id="dm-101" checked="checked">
<label for="dm-101">DM_101</label>
<input type="radio" id="delivery-method-2">
<label for="delivery-method-2">Delivery Method 2</label>*@
@{
foreach(var dp in Model.DpRestrictedList)
{
@Html.RadioButtonFor(model => model.DeliveryPointRestrictionId, dp);
}
}
</div>
</fieldset>
</div>
使用语句和示例:
@model WorkstreamX.Web.Core.ViewModels.ActivationCampaignViewModel
...
<div class="col-md-4">
<label for="headline">Campaign</label>
@Html.EditorFor(model => model.CampaignName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CampaignName)
</div>
上面是视图中的using语句,以及如何在其他地方使用它的示例。当我检查时,不仅列表为空,而且循环语句中的模型也为空。此时是否需要在控制器中更新视图模型?这就是我要尝试的方法,我只想陈述这个问题,也许找出原因。这里的任何建议都非常感谢。
[edit]我如何解决此问题:
我在视图中添加了一个参数:
在return View();
之前
在return View(new ActivationCampaignViewModel());
由于我以前似乎有一个模型,所以我仍然不太明白为什么会这样。我以为是因为我没有调用构造函数,所以该列表没有被构造并完全失效。
答案 0 :(得分:0)
您的代码应类似于以下代码。
Public ActionResult GetEmployee()
{
var employee = GetEmployee();
return View(employee);
}
@model IEnumerable<Appname.ViewModel.Employee>
@{
foreach(var data in Model) {}
}
答案 1 :(得分:0)
我如何解决此问题:
我在视图中添加了一个参数:
在return View();
之前
在return View(new ActivationCampaignViewModel());
由于我以前似乎有一个模型,所以我仍然不太明白为什么会这样。我以为是因为我没有调用构造函数,所以该列表没有被构造并完全失效。