Dynamic year snap with dropdown

I am using MVC3 / Razor and want to associate a dropdown list with the current plus and the previous 3 year. For instance,

2011 2010 2009 2008 

How to do it? Please, help

+4
source share
2 answers

Add the view below to create a drop-down list (modify Model.Year to fix the property on the model)

 <div class="editor-field"> @Html.DropDownList("Years",new SelectList(ViewBag.Years as System.Collections.IEnumerable,Model.Year)) @Html.ValidationMessageFor(model => model.Year) </div> 

Add below, somewhere in your controller or helper class

  private void GetYears() { List<int> Years = new List<int>(); DateTime startYear = DateTime.Now; while (startYear.Year <= DateTime.Now.AddYears(3).Year) { Years.Add(startYear.Year); startYear = startYear.AddYears(1); } ViewBag.Years = Years; } 

Then add the line below so that any method is called to return the view (i.e. index)

GetYears ();

+5
source

Using the solution above, but with an alternative for GetYears ()

  private void GetYears() { ViewBag.Years = Enumerable.Range(DateTime.Now.Year, 4); } 
+1
source

All Articles