2016-04-27 15 views
1

保存我有一個對象Mytype,其中有一個對象item都有唯一的ID,所以ID1和ID2。如何在沒有viewbag,viewdata或JavaScript的情況下動態確定下拉列表中的所選項目

我有一個編輯表單,數據根據Mytype ID1加載。

public void Load(int id) 
{ 

    var db = new dbEntities(); 
    Mytypes = db.MyTypes.ToList(); 
    MyTypeList = new SelectList(Mytypes, "ID", "Name"); 
    // etc .... 

我有一個下拉列表,並希望它在該項目土地使用相同ID的項目ID(ID2)屬於與ID1到MyType的項目。

@Html.DropDownList("MyType_ID", Model.MyTypeList, 
     htmlAttributes: new { @class = "form-control", 
     required = "required", autofocus = "autofocus" }) 

是否有可能做到這一點,而無需使用ViewBagViewDataJS

+0

如果'Mything'是模型中的一個屬性,那麼只需設置其值以匹配其中一個選項並將其選中。 –

+0

@StephenMuecke我知道這聽起來很荒謬,你能告訴我一個例子嗎? –

+0

'var model = new MyModel(){Mything =「ID2」,MyList = .....};返回View(model);'(但請使用強類型助手 - @@ Html.DropDownListFor(m => m.Mything,Model.MyList,new {@class =「form-control」,autofocus =「autofocus」} )'(注意你的'required =「required」)有點無意義) –

回答

2

假設你模型有一個名爲MyType_ID屬性,然後將其值設置爲匹配選項值之一,在該選項時,視圖被呈現

public class MyModel 
{ 
    public string MyType_ID { get; set; } 
    public IEnumerable<SelectListItem> MyTypeList { get; set; } 
    .... 
} 

將被選擇並在控制器

MyModel model = new MyModel() 
{ 
    MyType_ID = "ID2", 
    MyTypeList = new SelectList(Mytypes, "ID", "Name") 
}; 
return View(model); 

並在視圖

@Html.DropDownList("MyType_ID", Model.MyTypeList, new { @class = "form-control", autofocus = "autofocus" }) 

或優選地,使用強類型xxxFor()方法

@Html.DropDownListFor(m => m.MyType_ID, Model.MyTypeList, new { @class = "form-control", autofocus = "autofocus" }) 
+0

這麼簡單。有時我看不到森林的樹木。乾杯 –

相關問題