Asp.net mvc LinQ对实体和强制转换值类型的问题';布尔值';在SelectListItem中设置SelectedValue的步骤
我想用selectedValue创建一个dropdownlist,代码如下:Asp.net mvc LinQ对实体和强制转换值类型的问题';布尔值';在SelectListItem中设置SelectedValue的步骤,asp.net-mvc,Asp.net Mvc,我想用selectedValue创建一个dropdownlist,代码如下: public static IEnumerable<SelectListItem> GenSectionList(int? sectionId) { SectionRepository sectionRep = new SectionRepository(); var sections = sectionRep.GetAllSections();
public static IEnumerable<SelectListItem> GenSectionList(int? sectionId)
{
SectionRepository sectionRep = new SectionRepository();
var sections = sectionRep.GetAllSections();
int i = sections.ToList().Count();
return sections.Select(s => new SelectListItem()
{
Text = s.Title,
Value = SqlFunctions.StringConvert((double)s.Id),
Selected = s.Id == sectionId.Value //The cast to value type 'Boolean' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
});
}
公共静态IEnumerable分区列表(int?sectionId)
{
SectionRepository sectionRep=新建SectionRepository();
var sections=sectionRep.GetAllSections();
int i=sections.ToList().Count();
返回sections.Select(s=>newselectListItem()
{
Text=s.标题,
Value=SqlFunctions.StringConvert((双精度)s.Id),
Selected=s.Id==sectionId.Value//转换为值类型“Boolean”失败,因为具体化的值为null。结果类型的泛型参数或查询必须使用可为null的类型。
});
}
如何修复此错误
谢谢 试试这个:
public static IEnumerable<SelectListItem> GenSectionList(int? sectionId)
{
SectionRepository sectionRep = new SectionRepository();
var sections = sectionRep.GetAllSections();
int i = sections.ToList().Count();
return sections.Select(s => new SelectListItem()
{
Text = s.Title,
Value = SqlFunctions.StringConvert((double)s.Id),
Selected = sectionId.HasValue ? s.Id == sectionId.Value : false
});
}
公共静态IEnumerable分区列表(int?sectionId)
{
SectionRepository sectionRep=新建SectionRepository();
var sections=sectionRep.GetAllSections();
int i=sections.ToList().Count();
返回sections.Select(s=>newselectListItem()
{
Text=s.标题,
Value=SqlFunctions.StringConvert((双精度)s.Id),
所选=sectionId.HasValue?s.Id==sectionId.Value:false
});
}
如果将空节ID传递给控制器(这是允许的,因为它是可空类型),它可能无法与实体的ID匹配,因此在这种情况下返回false…尝试以下操作:
public static IEnumerable<SelectListItem> GenSectionList(int? sectionId)
{
SectionRepository sectionRep = new SectionRepository();
var sections = sectionRep.GetAllSections();
int i = sections.ToList().Count();
return sections.Select(s => new SelectListItem()
{
Text = s.Title,
Value = SqlFunctions.StringConvert((double)s.Id),
Selected = sectionId.HasValue ? s.Id == sectionId.Value : false
});
}
公共静态IEnumerable分区列表(int?sectionId)
{
SectionRepository sectionRep=新建SectionRepository();
var sections=sectionRep.GetAllSections();
int i=sections.ToList().Count();
返回sections.Select(s=>newselectListItem()
{
Text=s.标题,
Value=SqlFunctions.StringConvert((双精度)s.Id),
所选=sectionId.HasValue?s.Id==sectionId.Value:false
});
}
如果您将null节ID传递给控制器(这是允许的,因为它是可为null的类型),那么它可能无法与实体的ID匹配,因此在本例中返回false