2013-02-25 64 views
0

貼我有一個下拉列表containining檢索值在下拉列表

{ 
    Select a title, 
    Mr, 
    Ms, 
    Mrs 
} 

這是這樣

//in model file 
Mymodel mm=new Mymodel(); 
mm.Titles=new [] 
{ 
    new SelectListItem{....} 
} 

..... 
//in view file and was set up inside a form 

@Html.DropDownListFor(m=>m.Title, Model.Titles,"Select a title"); 

初始化我點擊後提交按鈕,我想在下拉列表中得到slected值。

+0

您可以參考這裏 http://stackoverflow.com/questions/5371665/dropdownlistfor-selected-value – c0dem0nkey 2013-02-25 06:57:05

回答

2

你可以有到表單提交採取了同樣的觀點模型參數的[HttpPost]控制器動作:

[HttpPost] 
public ActionResult SomeAction(Mymodel model) 
{ 
    // the model.Title property will contain the selected value here 
} 

另外,Titles集合將不會被髮送到您的HttpPost行動。這就是HTML的工作原理。提交表單時,僅發送<select>元素的選定值。因此,如果您打算重新顯示相同的視圖,則需要重新填充Titles屬性。

例如:

[HttpPost] 
public ActionResult SomeAction(Mymodel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     // there was a validation error, for example the user didn't select any title 
     // and the Title property was decorated with the [Required] attribute => 
     // repopulate the Titles property and show the view 
     model.Titles = .... same thing you did in your GET action 
     return View(model); 
    } 

    // at this stage the model is valid => you could use the model.Title 
    // property to do some processing and redirect 
    return RedirectToAction("Success"); 
}