【问题标题】:How to get the selected item from a DropDownList?如何从 DropDownList 中获取所选项目?
【发布时间】:2015-08-09 21:19:44
【问题描述】:

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

        }

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!这就是问题所在,现在我明白为什么了。
    【解决方案2】:

    您的表单控件需要在表单标签内

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多