这个问题在这里已有答案:
我有一个类IEnumerable扩展,它需要返回项目列表
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items, int selectedValue)
{
return from item in items
select new SelectListItem
{
Text = item.GetPropertyValue("Ime"),
Value = item.GetPropertyValue("Id"),
Selected = item.GetPropertyValue("Id").Equals(selectedValue.ToString())
};
}
每当选择下拉列表并提交表单时,我都会收到NULLReferenceException。
到目前为止,我尝试按以下方式初始化
IEnumerable<object> items = new IEnumerable<items>();
但这不起作用。我做错了什么?
UPDATE
下拉式菜单
<div class="form-group row">
<div class="col-3">
<text>Vrsta vozila</text>
</div>
<div class="col-5">
<select asp-for="@Model.Garancija.VrsteVozilaID" asp-items="@Model.VrstaVozila.ToSelectListItem(Model.Garancija.VrsteVozilaID)" class="form-control"></select>
</div>
</div>
传递项目的IReflection方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Project.Extensions
{
public static class ReflectionExtension
{
public static string GetPropertyValue<T>(this T item,string propertyName)
{
return item.GetType().GetProperty(propertyName).GetValue(item, null).ToString();
}
}
}
VrsteVozila模型
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Project.Models
{
public class VrstaVozila
{
public int Id { get; set; }
[Required]
[MaxLength(20)]
public string Ime { get; set; }
}
}
之后,我创建ViewModel以显示所有下拉菜单
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Project.Models.ViewModels
{
public class GarancijaViewModel
{
public ProduzenaGarancija Garancija { get; set; }
public IEnumerable<Cjenovnik> Cijenovnik { get; set; }
public IEnumerable<Gorivo> Gorivo { get; set; }
public IEnumerable<MarkeVozila> MarkeVozila { get; set; }
public IEnumerable<ModeliVozila> ModeliVozila { get; set; }
public IEnumerable<Produkt> Produkt { get; set; }
public IEnumerable<VrstaMjenjaca> VrstaMjenjaca { get; set; }
public IEnumerable<VrstaVozila> VrstaVozila { get; set; }
}
}
如果要将空值作为空可枚举处理,我建议使用以下解决方案:
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items, int selectedValue)
{
if (items === null) return Enumerable.Empty<T>();
return items.Select(item => new SelectListItem {
Text = item.GetPropertyValue("Ime"),
Value = item.GetPropertyValue("Id"),
Selected = item.GetPropertyValue("Id").Equals(selectedValue.ToString())
});
}