What is the best way to code up a Month and Year drop down list for ASP.NET?

后端 未结 8 1495
北荒
北荒 2020-12-16 00:31

I have an internal application that I needs to have a drop down list for two date type elements: Month and Year. These values are not in

相关标签:
8条回答
  • 2020-12-16 01:20

    You can try this... Ref Here:

    http://allinworld99.blogspot.com/2015/01/bind-monthsyear-dropdownlist-c-aspnet.html

    for (int i = 1; i <= 12; i++)
    {
        drpBMonth.Items.Add(new System.Web.UI.WebControls.ListItem(DateTimeFormatInfo.CurrentInfo.GetMonthName(i), i.ToString()))};
    
    0 讨论(0)
  • 2020-12-16 01:22

    For ASP.NET MVC this is what I'm doing.

    Note I prefer to use a codebehind for things like this - its still part of the view and there's nothing wrong with the view constructing a SelectList.

    PaymentControl.ascx

     <%= Html.DropDownList("ExpirationMonth", ExpirationMonthDropdown)%> / 
     <%= Html.DropDownList("ExpirationYear", ExpirationYearDropdown)%>
    

    PaymentControl.ascx.cs

    public partial class PaymentControl : ViewUserControl<CheckoutModel>
        {
            public IEnumerable<SelectListItem> ExpirationMonthDropdown
            {
                get
                {
                    return Enumerable.Range(1, 12).Select(x =>
    
                        new SelectListItem()
                        {
                            Text = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[x - 1] + " (" + x + ")",
                            Value = x.ToString(),
                            Selected = (x == Model.ExpirationMonth)
                        });
                }
            }
    
            public IEnumerable<SelectListItem> ExpirationYearDropdown
            {
                get
                {
                    return Enumerable.Range(DateTime.Today.Year, 20).Select(x =>
    
                    new SelectListItem()
                    {
                        Text = x.ToString(),
                        Value = x.ToString(),
                        Selected = (x == Model.ExpirationYear)
                    });
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题