用于下拉列表的ASP.Net MVC视图模型?

时间:2013-07-16 20:36:02

标签: asp.net-mvc

我正在尝试使用MVC中生成的月份下拉列表。 我的viewmodel是:

public class MyViewModel{

   public MyViewModel()
   {
      var monthNames = DateTimeFormatInfo.CurrentInfo.MonthNames.Take(12).ToList();
Months = new SelectList(monthNames.Select(m=> new{Id=monthNames.IndexOf(m)+1, Name=m}).ToList(),"Id","Name");
   }

   public IEnumerable<SelectListItem> Months{ get; set; }

   public string Month{ get; set; }

}

我的观点是:

@Html.DropDownListFor(model=>model.Month, new SelectList(Model.Months))

问题是Months属性总是返回一个空值,因此在尝试渲染DDL时页面会出错。

看起来很简单。我错过了什么?

2 个答案:

答案 0 :(得分:2)

您错过了实际将Months属性设置为其他而非null的部分。

您应该只在属性上定义一个自定义getter,以便它始终返回一个可枚举:

public IEnumerable<SelectListItem> Months
{
    List<string> monthNames = DateTimeFormatInfo.CurrentInfo.MonthNames.Take(12).ToList();
    foreach (var month in monthNames)
    {
        yield return new SelectListItem
        {
            Value = monthNames.IndexOf(month) + 1,
            Text = month
        };
    }
}

答案 1 :(得分:2)

使用模板作为另一种可能的解决方案:

// in your model, decorate it to use the template
[UIHint("MonthName")]
public String Month { get; set; }

然后在~/Views/Shared/EditorTemplates/MonthName.cshtml

@model String
@Html.DropDown(
  String.Empty,
  @Model,
  new SelectList(
    System.Globalization.DateTimeFormatInfo.CurrentInfo.MonthNames
      .Where(x => !String.IsNullOrEmpty(x))
      .Select((x,y) => new { Text = x, Value = y + 1 }),
    "Value",
    "Text"
  )
)

最后,在你看来:

@Html.EditorFor(x => x.Month)

虽然这在固定列表(例如几个月)上真的值得,而不是基于正在显示的视图可能是动态的。

相关问题