[MVC]產生年度的DropDownList

[MVC]產生年度的DropDownList

系統中常常會使用到年度的DropDownList給使用者選擇,所以可建立公用的Model來使用它!

所以建立一個SearchYearList Class,裡面有StartSearchYear、EndSearchYear及一個GetYearListItems的Method!

public class SearchYearList
{
    
    //開始年度
    public static int StartSearchYear = 1997;
    //結尾年度
    public static int EndSearchYear = DateTime.Now.Year;

	
    /// <summary>
    /// 依開始、結尾年度來產生年度的List
    /// </summary>
    /// <param name="selectedYear"></param>
    /// <returns></returns>
    public static IEnumerable<SelectListItem> GetYearListItems(int? selectedYear)
    {
        var yearList = new List<SelectListItem>();

	
        for (int i = StartSearchYear; i <= EndSearchYear; i++)
        {
            yearList.Add(new SelectListItem
            {
                Text = i.ToString(),
                Value = i.ToString(),
                Selected = (selectedYear == i)
            });
        }
        return yearList;
    }
}

而在View中using Models,再直接使用它就可以了!

@using MyAP.Models; 
@Html.Label("年度")
@Html.DropDownList("cboSearchYear", SearchYearList.GetYearListItems(SearchYearList.StartSearchYear))
~
@Html.DropDownList("cboEndYear", SearchYearList.GetYearListItems(SearchYearList.EndSearchYear))

image

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^