Reputation: 2050
I am new to asp.net MVC 3. I want to create dropdown for each year, month and day. I created a helper class that collects common function. See below.
Common
Public Shared Function GetYearsList() As List(Of SelectListItem)
Dim items As New List(Of SelectListItem)
For i = -1 To 2500
Dim item As New SelectListItem
item.Text = Now.AddYears(i).Year.ToString()
item.Value = Now.AddYears(i).Year.ToString()
If i = Now.Year Then
item.Selected = True
End If
items.Add(item)
Next
Return items
End Function
In the Controller class.
Function Index() As ActionResult
ViewData("Year") = Command.GetYearsList()
ViewData("Month") = Command.GetMonthsList()
ViewData("Day") = Command.GetDaysList()
Return View()
End Function
In the View page.
@Html.DropDownList("Year", DirectCast(ViewData("Year"), List(Of SelectListItem)), New With {.onchange = "setDate();"})
But it didnot select current year. How can I do to select current year. Otherwise has other solution for that? Thanks all.
Upvotes: 0
Views: 438
Reputation: 2381
I show what you want but in C#. I think you can easily rewrite it to VB.
Firs of all, make a view model class for the view.
public class SomeViewModel
{
public SomeViewModel()
{
this.Years = new List<int>();
for (int i = -1; i <= 2500; i++)
{
this.Years.Add(DateTime.Now.AddYears(i).Year);
}
this.SelectedYear = DateTime.Now.Year;
}
public int SelectedYear { set; get; }
public List<int> Years { set; get; }
}
It has a property that contains the years, and another for the selected one.
Second, make a simple controller method:
public ActionResult Index()
{
var model = new SomeViewModel();
return View(model);
}
After this, make your strongly typed view:
@model YourAppNameSpace.ViewModels.SomeViewModel
...
@Html.DropDownListFor(model => model.SelectedYear, new SelectList(Model.Years))
It will make a DropDownList containing the years, and the selected year is the current year.
Upvotes: 1