Wednesday, March 11, 2015

Get all month names from DateTime in C#

Here is a method that returns a set of key values for each month:

In Controller, create a method 'GetAllMonths', and put the values in ViewBag, and then use that in your View for eg.:

     ViewBag.AllMonthsOfYear = new SelectList(GetAllMonths(),"Key","Value","");


  public IEnumerable<KeyValuePair<intstring>> GetAllMonths()
        {
            for (int i = 1; i <= 12; i++)
            {
                yield return new KeyValuePair<intstring>(i, DateTimeFormatInfo.CurrentInfo.GetMonthName(i));
            }
        }



  @Html.DropDownList("ddlMonths", (SelectList)ViewBag.AllMonthsOfYear, "--Select Month--",null

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More