2015-08-09 42 views
2

我知道這是一個很多人在網站上回答的問題,但沒有解決方案似乎對我的問題起作用。 我是MVC的新手,不知道如何將下拉列表中的選定項目發送給控制器。如何從DropDownList中獲取所選項目?

public class MonthDropDownList 
    { 
     public IEnumerable<SelectListItem> Months 
     { 
      get 
      { 
       return DateTimeFormatInfo 
         .InvariantInfo 
         .MonthNames 
         .Where(m => !String.IsNullOrEmpty(m)) 
         .Select((monthName, index) => new SelectListItem 
         { 
          Value = (index + 1).ToString(), 
          Text = monthName 
         }); 
      } 
     } 

     public int SelectedMonth { get; set; } 

    } 

這是我的觀點:

@model Plotting.Models.MonthDropDownList 

@Html.DropDownListFor(x => x.SelectedMonth, Model.Months) 

@using (Html.BeginForm("MonthlyReports", "Greenhouse", FormMethod.Post)) 
{ 
<input type="submit" name="btnSubmit" value="Monthly Report" /> 
} 

這裏是我應該使用哪種選擇日期的ActionResult:

public ActionResult MonthlyReports(MonthDropDownList Month) 
     { 

      Debug.Write("Month" + Month.SelectedMonth);// <- always = 0 
      InitChartModel(); 
      cDate.DateTitle = "Day"; 
      string msg = dal.Connection("month"); 
      List<Greenhouse> greenhouse = dal.FindIfDMY("month" , Month.SelectedMonth , msg); 
      cDate.DateData = GetChart(greenhouse, "month"); 

      return View("MonthlyReports", cDate); 

     } 

回答

3

您應該移動你的DropDownList到你的表單中。

@model Plotting.Models.MonthDropDownList 

@using (Html.BeginForm("MonthlyReports", "Greenhouse", FormMethod.Post)) 
{ 
    @Html.DropDownListFor(x => x.SelectedMonth, Model.Months) 
    <input type="submit" name="btnSubmit" value="Monthly Report" /> 
} 
+0

謝謝!這是問題,現在我明白了爲什麼。 – Maria

1

您的表單控件需要表單標籤內

@using (Html.BeginForm("MonthlyReports", "Greenhouse", FormMethod.Post)) 
{ 
    @Html.DropDownListFor(x => x.SelectedMonth, Model.Months) // move here 
    <input type="submit" name="btnSubmit" value="Monthly Report" /> 
} 
相關問題