2011-02-28 89 views
5

我有一個模型,該模型具有public List<string> Hour { get; set; } 和構造模型綁定下拉列表中選擇值

public SendToList() 
    { 
     Hour = new List<string> { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; 
    } 

我的問題是,爲什麼我沒有拿到一個選定值這個

@Html.DropDownListFor(model => model.Hour, Model.Hour.Select( 
       x => new SelectListItem 
       { 
        Text = x, 
        Value = x, 
        Selected = DateTime.Now.Hour == Convert.ToInt32(x) 
       } 
      )) 

但我在這裏得到了一個選定的值。

@Html.DropDownList("Model.Hour", Model.Hour.Select( 
       x => new SelectListItem 
       { 
        Text = x, 
        Value = x, 
        Selected = DateTime.Now.Hour == Convert.ToInt32(x) 
       } 
      )) 

有什麼區別?

回答

11

因爲您需要將選定的值分配給您的模型。

所以我會建議你採用以下方法。讓我們先從視圖模型:

public class MyViewModel 
{ 
    // this will hold the selected value 
    public string Hour { get; set; } 

    public IEnumerable<SelectListItem> Hours 
    { 
     get 
     { 
      return Enumerable 
       .Range(0, 23) 
       .Select(x => new SelectListItem { 
        Value = x.ToString("00"), 
        Text = x.ToString("00") 
       }); 
     } 
    } 
} 

你可以填充控制器內該視圖模型:

public class HomeController: Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      // Set the Hour property to the desired value 
      // you would like to bind to 
      Hour = DateTime.Now.Hour.ToString("00") 
     }; 
     return View(model); 
    } 
} 

,並在你看來簡單:

@Html.DropDownListFor(
    x => x.Hour, 
    new SelectList(Model.Hours, "Value", "Text") 
) 
+0

感謝你爲這個。使發送具有選定值的道具。愛範圍聲明,不知道它。我還可以在會議記錄中使用它嗎?我只想給出0,5,10的選項.... – 2011-02-28 13:18:21

+1

我知道它有點晚了,但要在您的評論中回答您的問題,您可以在where語句中進行模數化,例如.Where(x => x% 5 <= 0) – Sam 2011-08-11 12:35:17

相關問題