【发布时间】:2017-04-01 17:39:07
【问题描述】:
我创建了一个 ASP.NET Core Web 应用程序,它使用 Entity Framework Core 从我现有的数据库中读取数据。我想在视图中使用 FacilityNames 列表填充选择控件,以便在我的 FacilityRevenue 表中创建一个新条目。
我在 FacilityRevenue Controller 上的 Create 方法如下:
public IActionResult Create()
{
PopulateFacilityDropDownList();
return View();
}
private void PopulateFacilityDropDownList
(object selectedFacility = null)
{
var facilityQuery = from f in _context.FacilityMaster
orderby f.FacilityName
select f;
ViewBag.FacilityID = new SelectList(facilityQuery.AsNoTracking(), "FacilityID", "FacilityName", selectedFacility);
}
我的创建视图包含以下标记:
<label asp-for="FacilityName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="FacilityId" asp-items="ViewBag.FacilityID">
<option value="">-- Select Facility --</option>
</select>
<span asp-validation-for="FacilityName" class="text-danger" />
</div>
我的 FacilityRevenue 模型如下:
public partial class FacilityRevenue
{
public string FacilityName { get; set; }
public DateTime Date { get; set; }
public decimal? TotalInvoices { get; set; }
public decimal? TotalRevenue { get; set; }
public int RecordId { get; set; }
public int? FacilityId { get; set; }
public virtual FacilityMaster Facility { get; set; }
}
堆栈跟踪如下:
System.NullReferenceException: Object reference not set to an instance of an
object.
at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.Eval(Object container,
String expression)
at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.
GetListItemsWithValueField()
at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.
GenerateGroupsAndOptions(String optionLabel, IEnumerable`1 selectList,
ICollection`1 currentValues)
at
Microsoft.AspNetCore.Mvc.ViewFeatures.
DefaultHtmlGenerator.GenerateSelect(ViewContext viewContext, ModelExplorer
modelExplorer, String optionLabel, String expression, IEnumerable`1
selectList, ICollection`1 currentValues, Boolean allowMultiple, Object
htmlAttributes)
at
Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper.Process(TagHelperContext
context, TagHelperOutput output)
at
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.
ProcessAsync(TagHelperContext context, TagHelperOutput output)
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.
<RunAsync>d__0.MoveNext()
如何纠正上述错误并实现使用工具列表水合选择控件的功能?
【问题讨论】:
-
该错误是因为
ViewBag.FacilityID是null(可能是因为您提交了表单,然后返回视图却忘记重新填充ViewBag属性。但千万不要为属性使用相同的名称你绑定到SelectList -
+1 用于仅间接解决我的问题的问题:您的
facilityQuery返回整个对象,而不是特定字段,这就是我正在做的(导致相同的错误消息)。我需要至少返回一个Dictionary。
标签: c# asp.net-mvc entity-framework asp.net-core