如何创建允许用户选择月份的下拉列表?

时间:2017-01-10 17:37:52

标签: c# asp.net-mvc dynamic

现在我有了这个,一切正常。

PossibleExpirationMonths = creditCardInterpreter.GetPossibleMonths()

GetPossibleMonths方法:

    public List<dynamic> GetPossibleMonths()
    {
        return new List<dynamic>()
        {
            new {Display = "01 Jan", Value = 1 },
            new {Display = "02 Feb", Value = 2 },
            new {Display = "03 Mar", Value = 3 },
            new {Display = "04 Apr", Value = 4 },
            new {Display = "05 May", Value = 5 },
            new {Display = "06 Jun", Value = 6 },
            new {Display = "07 Jul", Value = 7 },
            new {Display = "08 Aug", Value = 8 },
            new {Display = "09 Sep", Value = 9 },
            new {Display = "10 Oct", Value = 10 },
            new {Display = "11 Nov", Value = 11 },
            new {Display = "12 Dec", Value = 12 }
        };
    }

以及我如何展示它:

@Html.DropDownListFor(model => model.ExpirationMonth, new SelectList(Model.PossibleExpirationMonths, "Value", "Display"), new { @class = "form-control" })

我遇到的问题是当我尝试测试方法并访问动态的显示和值属性时

returnedList.First().Display

我收到错误。 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:&#39; object&#39;不包含&#39;显示&#39;

的定义

我想在这里使用动态的原因是因为我不觉得我应该创建一个包含这么少信息的容器类。它只会造成臃肿,我想要更清洁。

有任何想法/建议吗?

1 个答案:

答案 0 :(得分:2)

问题是.First()始终返回类型Object。你可以尝试:

((dynamic)returnedList.First()).Display
但是,我认为你可能会重新发明轮子。为什么你没有使用DateTimePicker或类似的控件?您需要的所有内容都是DateTime(具体为DateTime.Month)的属性。对于网络,this solution效果很好。