如何从 DropDownList 中获取所选项目?

How to get the selected item from a DropDownList?

我知道这个问题在网站上有很多人回答,但似乎没有任何解决方案可以解决我的问题。 我是 MVC 的新手,不知道如何将下拉列表中的选定项发送到控制器。

 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);

        }

您的表单控件需要位于表单标签内

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

您应该将 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" />
}