c# - 在 C# ASP.NET MVC 中创建月份下拉列表

标签 c# asp.net-mvc c#-3.0

这个方法看起来很笨,有点重;有没有更好的方法来创建相同的东西(它用于 MVC View 下拉列表)

private List<KeyValuePair<int, string>> getMonthListDD
{
    get
    {
        var dDur = new List<KeyValuePair<int, string>>();
        dDur.Add(new KeyValuePair<int, string>(1, "January"));
        dDur.Add(new KeyValuePair<int, string>(2, "Febuary"));
        dDur.Add(new KeyValuePair<int, string>(3, "March"));
        dDur.Add(new KeyValuePair<int, string>(4, "April"));
        dDur.Add(new KeyValuePair<int, string>(5, "May"));
        dDur.Add(new KeyValuePair<int, string>(6, "June"));
        dDur.Add(new KeyValuePair<int, string>(7, "July"));
        dDur.Add(new KeyValuePair<int, string>(8, "August"));
        dDur.Add(new KeyValuePair<int, string>(9, "September"));
        dDur.Add(new KeyValuePair<int, string>(10, "October"));
        dDur.Add(new KeyValuePair<int, string>(11, "November"));
        dDur.Add(new KeyValuePair<int, string>(12, "December"));

        return dDur;
    }
}

最佳答案

在您的 View 模型中,您可以拥有一个 Months 属性:

public IEnumerable<SelectListItem> Months
{
    get 
    {
        return DateTimeFormatInfo
               .InvariantInfo
               .MonthNames
               .Select((monthName, index) => new SelectListItem
               {
                   Value = (index + 1).ToString(),
                   Text = monthName
               });
    }
}

可以直接绑定(bind)到 DropDownListFor:

<%= Html.DropDownListFor(x => x.SelectedMonth, Model.Months) %>

关于c# - 在 C# ASP.NET MVC 中创建月份下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2911714/

相关文章:

c#-3.0 - 在 C# 中调用部分方法

c# - NHibernate异常

c# - MVC 验证低于/高于其他值

asp.net-mvc - 使用 Recaptcha 对 Action 进行单元测试

javascript - 在 Ajax 调用后重定向到另一个页面?

c# - 如何在 C# 3.0 中的字符串数组中搜索特定字符串

winforms - 在 2 个列表框之间拖放

c# - 通过 C#.Net 创建/连接 VPN 连接

c# - 为什么基本页面不提供 OnNavigatedTo() 事件?

c# - 选择一个随机画笔