将null添加到下拉列表选项中



在我的ASP.NET MVC4应用程序上,我需要一个下拉列表来选择位置并将其ID插入表中。一些新闻适用于所有位置 - 因此,新闻中的locationId是无效的,以指出此信息。

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

这是我想象的,它将起作用 - 但是在最后一行值= dbnull.value(或简单的null)不允许。它只接受整数。我不能将" 0"用作该表上的外键约束,因此不允许0,因为位置表中没有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});

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

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

相关内容

最新更新