Watch this example on YouTube
1. Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Web.Mvc;
namespace WebApplication1.Models
{
public class DropDownListSample
{
public IEnumerable<SelectListItem> Months
{
get
{
int curMonth = DateTime.Now.Month;
return Enumerable.Range(1, 12).Select(x => new SelectListItem { Value = x.ToString("0"), Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x), Selected = (x == curMonth) });
}
}
public IEnumerable<SelectListItem> Years
{
get
{
int curYear = DateTime.Now.Year;
return Enumerable.Range(DateTime.Now.Year - 10, 11).Select(x => new SelectListItem { Value = x.ToString("0"),Text = x.ToString("0"), Selected = (x == curYear) }).Reverse();
}
}
}
}
2. Controller
public ActionResult Index()
{
var model = new DropDownListSample();
return View(model);
}
3. View
@model WebApplication1.Models.DropDownListSample
@using (Html.BeginForm("Index", "Home"))
{
@Html.DropDownListFor(x => x.Months , Model.Months, "", new { @id = "ddlMonth"})
@Html.DropDownListFor(x =>x.Years, Model.Years, "", new { @id = "ddlYear"})
}
No comments:
Post a Comment