0

I am trying to work with a generated Month dropdownlist in MVC. My viewmodel is:

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; }

}

My View is:

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

The problem is that the Months property always returns a null value so the page errors when trying to render the DDL.

Seems pretty simple. What am I missing?

4
  • There's nothing wrong with your code, so your problem is likely in something you're not showing. Are you doing this in a partial view for instance? Commented Jul 16, 2013 at 20:39
  • Yes it is in a partial Commented Jul 16, 2013 at 20:40
  • Why do we need to call .Take(12).ToList()? Commented Jul 16, 2013 at 21:00
  • 2
    @AlexeyAza: MonthNames actually returns a fixed String[13], so I'm assuming it was OPs way of removing the last empty element (though, IMHO, that kind of defeats the whole localization point). ;p Commented Jul 16, 2013 at 21:02

2 Answers 2

2

You're missing the part where you actually set the Months property to something other than null.

You should just define a custom getter on the property so it always returns an enumerable:

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
        };
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ya my cut and paste failed me and I didn't proof well. I edited my original example.
2

As another possible solution using templates:

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

Then in ~/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"
  )
)

And finally, in your view:

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

though this is really only worth while on fixed-lists (like months), and not for things that may be dynamic based on the view being displayed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.