RSS

Tag Archives: .NET

.NET MCV: Method parameters from HTML forms

A very simple thing that can cause problem, but really hard to spot since it is right under your nose:

View:

@using (Html.BeginForm("Result", "Home", FormMethod.Get))
{
    <fieldset>
        <legend>Enter your Birthday:</legend>
        <div>Year</div>
        @Html.DropDownList("Year", ViewBag.YearList as List<SelectListItem>,
            "Select a Year")
        <div>Month</div>
        @Html.DropDownList("Month", ViewBag.MonthList as List<SelectListItem>,
            "Select a Month")
        <div>Day</div>
        @@Html.DropDownList("Day", ViewBag.DayList as List<SelectListItem>,
            "Select a Day")
        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}


Controller

        public ActionResult Index()
        {
            ViewBag.YearList = Lab1Manager.getYearList();
            ViewBag.MonthList = Lab1Manager.getMonthList();
            ViewBag.DayList = Lab1Manager.getDayList();
            return View();
        }
       
        /// <summary>
        /// The names of the parameters must be the same as same as the select element id
        /// if the select id is not specified when using @Html.DropDownList()
        /// then it will default to the ViewBag item name
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="Month"></param>
        /// <param name="Day"></param>
        /// <returns></returns>
        public ActionResult Result(String Year, String Month, String Day)
        {
            ViewBag.MyDate = Year + "-" + Month + "-" + Day;
            return View();
        }

Result receives parameters from the form inside Index page, and the names of the these parameters must be EXACTLY same as the select id names, else it won’t work.

 
Leave a comment

Posted by on September 10, 2013 in Knowledge

 

Tags: , ,