Maria
Maria

Reputation: 313

How to get the selected item from a DropDownList?

I know this is a question that many people responded on the site , but no solution seems to work to my problem. I am new to MVC and do not know how to send the selected item in the drop down list to the controller .

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

    }

Here is my view :

@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" />
}

And here is the ActionResult in which i should use the selected date :

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

        }

Upvotes: 2

Views: 96

Answers (2)

Medeni Baykal
Medeni Baykal

Reputation: 4333

You should move your DropDownList into your form.

@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" />
}

Upvotes: 3

user3559349
user3559349

Reputation:

Your form control needs to be inside the form tags

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

Upvotes: 1

Related Questions