user2609980
user2609980

Reputation: 10474

How to display NULL values in view in DropDownListFor

I have the following DropDownListFor. The ShopId entry is nullable and I would like to keep it that way. This dropdownlist displays the shops as follows:

@Html.DropDownListFor(m => weekDay.Shop.ShopId,
    new SelectList(Model.ShopItems,
        "ShopId",
        "Name",
        weekDay.Shop.ShopId),
        ""
)

Now I want to have the application not give a System.NullReferenceException: Object reference not set to an instance of an object-error when the value is NULL. I've tried using if-statements and try-catches. Besides being ugly they do not work.

Does anyone have an idea how I can display a default empty string when the value in the database is NULL?

/edit The same question in another way. The controller looks as follows:

var viewModel = new ShopWeekDayViewModel
                    {
                        ShopItems = db.Shops.ToList(),
                        WeekDays = db.WeekDays.ToList()
                    };

How can I filter empty the null values in ShopItems and change them into empty strings?

/edit 2

The values in the database look as follows:

WeekDayId    ShopId    Day
1            NULL      Zondag
2            1         Maandag
3            1         Dinsdag
4            1         Woensdag
5            1         Donderdag
6            2         Vrijdag
7            NULL      Zaterdag

When I change the NULL values to 1 or 2 the code works...

Upvotes: 0

Views: 275

Answers (1)

John H
John H

Reputation: 14655

I don't really understand why you'd want to show an invalid option for a dropdown. If it's not a valid option, why allow a user to select it at all? Just filter out the null values completely:

ShopItems = db.Shops.Where(s => s.ShopId != null).ToList()

Having said that, if you're dead set on doing it, you could try the following:

ShopItems = db.Shops.Select(s => new Shop {
    ShopId = s.ShopId,
    Day = s.ShopId != null ? s.Day : "Your default value"
}).ToList()

However, if you're using LINQ to Entities, this will generate the following exception:

The entity or complex type Shop cannot be constructed in a LINQ to Entities query

I'm not sure if this will also occur with LINQ to SQL, but you can get around that by first projecting on to an anonymous type and then projecting on to a Shop:

ShopItems = db.Shops.Select(s => new {
    ShopId = s.ShopId,
    Day = s.ShopId != null ? s.Day : "Your default value"
}).Select(anon => new Shop {
    ShopId = anon.ShopId,
    Day = anon.Day
}).ToList()

Upvotes: 1

Related Questions