Reputation: 818
On my ASP.NET MVC4 application, I need a dropdown-list to select a Location and insert its ID into a table, say News. Some news apply to ALL Locations - therefore the LocationID in News is Nullable, to indicate this.
So I need to add "ALL Locations" to the dropdown.
This is how I imagined, it would work - but on the last line Value = DBNull.Value (or simple null) is not allowed. It only accepts an integer. I CANNOT use "0" as foreign key constraints on that table do not allow 0, because there is no ID=0 in Locations-table
var locations = db.Locations.Select(c => new { DisplayText = c.Location, Value = c.ID }).ToList();
locations.Insert(0, new { DisplayText = "All Locations", Value = DBNull.Value });
return Json(new { Result = "OK", Options = locations});
How can I add this to the options-list?
Upvotes: 0
Views: 243
Reputation: 9763
The basis of your locations anonymous object is created in the new {}
operator in your Linq statement. If you need to allow for NULL, then... new { DisplayText = c.Location, Value = (int?)c.ID }
explicitly set the anonymous type's Value parameter as nullable int. Then you can do Value = null
on the next line when inserting.
Upvotes: 1