我正在用C#和.NET Framework 4.7開發ASP.NET MVC應用程序。從dropdownlist selectitems中選擇ID和名稱時出錯
我有這個class
,我傳遞到視圖:
public class CreateBatchViewModel
{
private readonly List<GenericIdNameType> lines;
public bool IsWizard { get; set; }
public IEnumerable<SelectListItem> LineItems
{
get { return new SelectList(lines, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public List<Data.Batch> Batches { get; set; }
public CreateBatchViewModel(bool isWizard) : this()
{
IsWizard = isWizard;
}
public CreateBatchViewModel()
{
lines = new List<GenericIdNameType>();
}
public CreateBatchViewModel(List<Data.Line> dataLines, bool isWizard)
{
IsWizard = isWizard;
if (dataLines == null)
throw new ArgumentNullException("dataLines");
lines = new List<GenericIdNameType>(dataLines.Count);
GenericIdNameType genericType = new GenericIdNameType()
{
Id = null,
Name = Resources.Resources.CreateBatchViewModelDontHave
};
lines.Add(genericType);
foreach (Data.Line line in dataLines)
{
genericType = new GenericIdNameType()
{
Id = line.LineId.ToString(),
Name = line.Name
};
lines.Add(genericType);
}
}
}
而這正是我在視圖中使用LineItems
:
@Html.DropDownListFor(m => m.Batches[index].LineId, new SelectList(Model.LineItems, "Id", "Name", Model.Batches[index].LineId))
但我收到此錯誤信息:
System.Web.HttpException:'DataBinding: 'System.Web.Mvc.SelectListItem'does不包含名稱爲「Id」的 屬性。
我不明白,因爲我有一個Id
和Name
(get { return new SelectList(lines, "Id", "Name"); }
)
我試圖從下拉列表中刪除Id
和name
:
@Html.DropDownListFor(m => m.Batches[index].LineId, new SelectList(Model.LineItems, Model.Batches[index].LineId))
但現在它顯示System.Web.Mvc.SelectListItem
在選擇。
我在做什麼錯?