我對使用MVC和LINQ理解某些數據類型和數據集有困難。我正在嘗試填充下拉列表。populate dropdownlist for mvc
我收到以下錯誤(在下面的代碼說明)
「無法創建類型‘vps_intranet.Models.Part’的恆定值,只有原始類型或枚舉類型在支持這個背景「。
PartsController.cs
private List<Part> partsNotPartOfStructure(int partID)
{
Part mainPart = db.Parts.Find(partID);
//var alreadySelected = db.Parts.Select(p => p.PartStructures_comp).Distinct();
List<Part> parts = new List<Part>();
List<PartStructures> excludeList = db.PartStructures1
.Where(p => p.mainPart_id == partID).ToList();
parts = db.Parts.Where(c => c.PartStructures_comp
.Except((List<PartStructures>) excludeList)).ToList();
//The line above gives the error...
//Unable to create a constant value of type 'vps_intranet.Models.Part'.
//Only primitive types or enumeration types are supported in this context.**
return parts;
}
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Part part = await db.Parts.FindAsync(id);
if (part == null)
{
return HttpNotFound();
}
ViewData["AvailableParts"] = partsNotPartOfStructure(id.Value);
return View(part);
}
Details.cshtml
@model vps_intranet.Models.Part
@{
var fullList = (IEnumerable<vps_intranet.Models.Part>) ViewData["AvailableParts"];
var availableParts = fullList.Select(p => new SelectListItem { Text = p.partNo.ToString(), Value = p.id });
}
...
@Html.DropDownListFor(model => model.PartStructures_comp, availableParts));
我需要做什麼改變嗎?
確實[這](http://stackoverflow.com/questions/18929483/unable-to-create-a-constant-value-of-type -only-primitive-types-or-enumeration-ty)有幫助嗎? –
您正嘗試在兩種不同的數據類型之間使用「排除」。你有'Part'類,然後是'List'。按部件進行。首先,獲取零件。然後,將其轉換爲零件結構列表,然後執行排除 –
您可能想查看[ASP.Net MVC中的DropDownList](http://stackoverflow.com/questions/37818949/best-programming-practice-of -using-dropdownlist-in-asp-net-mvc/37819577#37819577) – Win