向DropdownList-options添加NULL

时间:2012-11-08 21:04:17

标签: c# asp.net-mvc

在我的ASP.NET MVC4应用程序中,我需要一个下拉列表来选择一个位置并将其ID插入表中,比如说新闻。 一些新闻适用于所有地点 - 因此新闻中的LocationID是可以为空的,以表明这一点。

所以我需要在下拉列表中添加“所有位置”。

这是我想象的,它会起作用 - 但是在最后一行不允许使用Value = DBNull.Value(或简单的null)。它只接受一个整数。我不能使用“0”因为该表上的外键约束不允许0,因为Locations-table中没有ID = 0

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

如何将其添加到选项列表?

1 个答案:

答案 0 :(得分:1)

您的位置匿名对象的基础是在Linq语句的new {}运算符中创建的。如果需要允许NULL,则... new { DisplayText = c.Location, Value = (int?)c.ID }将匿名类型的Value参数显式设置为nullable int。然后,您可以在插入时在下一行执行Value = null