如何解决为什么我的 SelectList 不喜欢 IList 的内容?
这是我的 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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。