问题描述
这是我的 Razor 页面中的相关代码:我收到一条错误消息,指出对象(在选择元素行上)未设置为对象的实例。
<select asp-for="EmployeeLocation.EmployeeID" asp-items="@Model.EmployeeSelectList">
这是我的 PageModel 类中的相关代码:
public EmployeeLocation EmployeeLocation { get; set; }
public Employee Employee { get; set; }
public class JoinResult
{
public int EmployeeID;
public string LastName;
}
private IQueryable<JoinResult> JoinResultIQueryable;
private IList<JoinResult> JoinResultIList;
public SelectList EmployeeSelectList;
public async Task OnGetAsync()
{
// Get the employee's locations.
List<int> EmployeeLocationsList = HttpContext.Session.Getobject<List<int>>("EmployeeLocationsList");
// Populate the employee select list.
JoinResultIQueryable = (
from e in IDDSContext.Employee
join p in IDDSContext.Position on e.PositionID equals p.PositionID
join el in IDDSContext.EmployeeLocation on e.EmployeeID equals el.EmployeeID
where e.Active == true
&& e.PositionID != 1 // Do not display the super administrator's data.
&& EmployeeLocationsList.Contains(el.LocationID)
select new JoinResult
{
EmployeeID = e.EmployeeID,LastName = e.LastName
});
JoinResultIList = await JoinResultIQueryable
.distinct()
.OrderBy(jr => jr.LastName)
.ToListAsync();
// display the results in the Output window. Just done to show contents of JoinResultIList (see below).
foreach (var item in JoinResultIList)
{
Debug.WriteLine("[" + item.EmployeeID + "][" + item.LastName + "]");
}
// ***** The problem seem to occur here. Evidently,the SelectList doesn't like contents of the IList. Why is this happening?
EmployeeSelectList = new SelectList(JoinResultIList,"EmployeeID","LastName");
}
以下是 JoinResultIList 的内容(在输出窗口中):
[4][Anderson (OH)]
[30][Becon (OH)]
[26][Smith (OH)]
[25][Stevens (OH)]
解决方法
好的。所以,这是我想出的解决方案。
// Get the employee's locations.
List<int> EmployeeLocationsList = HttpContext.Session.GetObject<List<int>>("EmployeeLocationsList");
// Populate the employee select list.
IQueryable JoinResultIQueryable = (
from e in IDDSContext.Employee
join p in IDDSContext.Position on e.PositionID equals p.PositionID
join el in IDDSContext.EmployeeLocation on e.EmployeeID equals el.EmployeeID
where e.Active == true
&& e.PositionID != 1 // Do not display the super administrator's data.
&& EmployeeLocationsList.Contains(el.LocationID)
orderby e.LastName,e.FirstName
select new
{
EmployeeID = e.EmployeeID,Employee = $"{e.LastName},{e.FirstName} ({p.Position1})",});
EmployeeSelectList = new SelectList(JoinResultIQueryable,"EmployeeID","Employee");