如何从DropDownList中获取所选项?

时间:2015-08-09 13:11:29

标签: c# asp.net asp.net-mvc html.dropdownlistfor

我知道这是许多人在网站上回复的问题,但似乎没有任何解决方案可以解决我的问题。 我是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);

        }

2 个答案:

答案 0 :(得分: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" />
}

答案 1 :(得分: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" />
}