dynamic year binding with drop down
I'm using MVC3/Razor and want to bind a drop down with current plus 3 previous year Number like,
2011
2010
2009
2008
Ho开发者_高级运维w to do this? Please help
Add the below to view to create the dropdownlist (change Model.Year to correct 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 to 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;
}
And then add below line to whatever method will be called to return the view (i.e. Index)
GetYears();
Using above solution but with an alternative for GetYears()
private void GetYears()
{
ViewBag.Years = Enumerable.Range(DateTime.Now.Year, 4);
}
精彩评论