2017-07-26 33 views
1

我正在用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」的 屬性。

我不明白,因爲我有一個IdNameget { return new SelectList(lines, "Id", "Name"); }

這些都是SelectItems領域: enter image description here

我試圖從下拉列表中刪除Idname

@Html.DropDownListFor(m => m.Batches[index].LineId, new SelectList(Model.LineItems, Model.Batches[index].LineId)) 

但現在它顯示System.Web.Mvc.SelectListItem在選擇。

我在做什麼錯?

回答

2

LineItems屬性的typeof IEnumerable<SelectListItem>SelectListItem包含屬性ValueText

更改視圖代碼

@Html.DropDownListFor(m => m.Batches[index].LineId, 
    new SelectList(Model.LineItems, "Value", "Text", Model.Batches[index].LineId)) 

或屬性更改爲IEnumerable<Line> LineItems,不產生方法的一SelectList,並保留現有的視圖代碼

2

好了,SelectListItem沒有,本身,包含財產標識。這是一個關鍵 - 價值關係,您可以將文本視爲關鍵。 瞭解更多here。 基本上,我猜你想要做這樣的事情:

var selectListItems = new List<SelectListItem>(); 
foreach(var productionOrder in ProductionOrders){ 
selectListItems.Add(new SelectListItem 
       { 
        Value = productionOrder.Id, 
        Text = productionOrder.Name 
       })} 

在控制器中,然後發送所選項目的ID selectListItems和屬性到模型(視圖模型)。 然後,你可以簡單地做這在您的視圖:

@Html.DropDownListFor(m => m.SelectedListItemId, Model.SelectListItems, new { @class = "form-control" }) 

然後將下拉的ID最終是你的ID和顯示名稱是你的名字。