-1

I need to display month and year list to dropdownlist in MVC but i encounter an error "Object reference not set to an instance of an object."

MODEL

public class AccountingViewModel
    {
    public string StartMonth { get; set; }

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

VIEW

    @model TrackAndTrace.ViewModel.AccountingViewModel
@using (Html.BeginForm("AccountingReport", "Report", FormMethod.Post))
    {
    <div class="form-group">
                    @Html.LabelFor(model => model.StartMonth)
                    @Html.DropDownListFor(model=>model.StartMonth,Model.Years)
                    @Html.ValidationMessageFor(model => model.StartMonth)
    </div>
     }
tereško
  • 58,060
  • 25
  • 98
  • 150
Reynan
  • 163
  • 1
  • 1
  • 11

1 Answers1

0
This is solution of your problem.

 Replace this code with your code in your AccountingView model.

 public IEnumerable<SelectListItem> Months
        {
            get
            {
                return DateTimeFormatInfo
                       .InvariantInfo
                       .MonthNames
                       .TakeWhile(monthName => monthName != String.Empty)
                       .Select((monthName, index) => new SelectListItem
                       {
                           Value = (index +     1).ToString(CultureInfo.InvariantCulture),
                           Text = string.Format("({0}) {1}", index + 1, monthName)
                       });
            }
        }

Replace this code with your view code

@Html.DropDownListFor(model => model.StartMonth, new     SelectList(Model.Months, "Value", "Text", " "))
Dilip Oganiya
  • 1,504
  • 12
  • 20