[英]Fetch employee information by selecting employee_id from DropDownList
[英]Error selecting Id and Name from dropdownlist selectitems
我正在使用C#和.NET Framework 4.7開發ASP.NET MVC應用程序。
我有這個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);
}
}
}
這是我在View中使用LineItems
的地方:
@Html.DropDownListFor(m => m.Batches[index].LineId, new SelectList(Model.LineItems, "Id", "Name", Model.Batches[index].LineId))
但我收到此錯誤消息:
System.Web.HttpException:'數據綁定:'System.Web.Mvc.SelectListItem'不包含名稱為'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))
但是現在它在Select中顯示System.Web.Mvc.SelectListItem
。
我究竟做錯了什么?
您的LineItems
屬性是IEnumerable<SelectListItem>
並且SelectListItem
包含屬性Value
和Text
。
將查看代碼更改為
@Html.DropDownListFor(m => m.Batches[index].LineId,
new SelectList(Model.LineItems, "Value", "Text", Model.Batches[index].LineId))
或將屬性更改為IEnumerable<Line> LineItems
並且不要在方法中創建SelectList
並保留現有的視圖代碼
好吧,SelectListItem本身不包含屬性Id。 這是一個鍵值關系,您可以在其中將文本視為鍵。 在這里閱讀更多。 基本上,我想您想執行以下操作:
var selectListItems = new List<SelectListItem>();
foreach(var productionOrder in ProductionOrders){
selectListItems.Add(new SelectListItem
{
Value = productionOrder.Id,
Text = productionOrder.Name
})}
在控制器中,然后將selectListItems和所選項目ID的屬性發送到模型(viewmodel)中。 然后,您可以在自己的視圖中簡單地執行此操作:
@Html.DropDownListFor(m => m.SelectedListItemId, Model.SelectListItems, new { @class = "form-control" })
然后將以下拉列表的ID作為您的ID,並以顯示的名稱作為您的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.