开发者

Problem with LinQ to Entities and cast a value type 'Boolean' to set SelectedValue in SelectListItem

开发者 https://www.devze.com 2023-01-28 10:22 出处:网络
I want to create a dropdownlist with selectedValue following below code: public static IEnumerable<SelectListItem> GenSectionList(int? sectionId)

I want to create a dropdownlist with selectedValue following below code:

    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.Titl开发者_JAVA技巧e, 
            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.
        });
    }

How to fix this error?

Thanks!


Try this:

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     
    });
}

If you pass in a null section ID to the controller (as you allow because it is a nullable type), it can't possibly match the ID of your entity so return false in this case...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号