2017-05-24 16 views
1

我正在創建多選列表框。我能夠成功地將項目從模型渲染到列表框。以下是我的代碼:M-V-C:如何在編輯模式下獲取或指示列表框中的選定項目?

屬性

public IEnumerable<SelectListItem> carTypes { get; set; } 
public IEnumerable<string> selectedCarTypes { get; set; } 

創建操作

public ActionResult Create() 
{ 
    List<SelectListItem> selectListItem = new List<SelectListItem>(); 

    foreach(CarType type in db.CarTypes) 
     { 
      SelectListItem item = new SelectListItem() 
      { 
       Text = type.Name, 
       Value = type.Id.ToString() 
      }; 
      selectListItem.Add(item); 
     } 

     Assigning assign = new Assigning(); 
     assign.carTypes = selectListItem; 
     return View(assign); 
} 

查看

@Html.ListBoxFor(model=>model.selectedCarTypes,Model.carTypes) 

ŧ他的問題是編輯行爲。我一直試圖突出顯示Edit View中的所有列表框,這些列表框是爲特定的AssignId選擇的。在列表框中有三個項目:現代,豐田和寶馬,我選擇寶馬和豐田和創建分配。現在,當我回到編輯視圖時,它應該突出顯示寶馬和豐田。

我參考了here,但沒有爲我工作。有沒有解決這個問題的方法?

修改:這是我Edit Action

public ActionResult Edit(int? id) 
{ 
    if (id == null) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
    } 
    Assigning assign = db.Assigning.Find(id); 
    if (assign == null) 
    { 
     return HttpNotFound(); 
    } 
    return View(assign); 
} 
+0

發表您的編輯方法List<string>。 – User3250

+0

完成。現在請檢查請 –

+0

你在Edit action中添加'carTypes'在哪裏?您需要在編輯時爲選定的車型設置爲「selected = true」。 – User3250

回答

1

您沒有設置您的模型時,編輯:

  1. Model.carTypes應該是所有CarTypes的List<SelectListItem>

  2. Model.selectedTypes應該是所有選擇值

0

你可以把它當作的SelectList這需要在你的情況下,選擇價值

public SelectList(IEnumerable items, object selectedValue)

@Html.DropDownListFor(n => n.selectedCarTypes, 
        new SelectList(Model.carTypes, Model.SelectedCarTypes)) 
+0

沒有工作。我需要列表框不下拉列表 –

相關問題