Kurkula
Kurkula

Reputation: 6762

Asp.Net MVC DropDownList issue

I am trying to display dropdown in my asp.net mvc application.I got strucked on setting the list items in Priorities. What would be my mistake here?

public IList<SelectListItem> Priorities { get; set; }
Priorities = new List<SelectListItem>();
Priorities.Add(new IList<SelectListItem>
                {
                    new SelectListItem { Text = "High", Value = "1"},
                    new SelectListItem { Text = "Low", Value = "0"}
                });

@Html.DropDownListFor(m => m.SelectedPriority, Model.Priorities, "Select one")

Upvotes: 0

Views: 153

Answers (2)

Thomas Taylor
Thomas Taylor

Reputation: 555

You can't instantiate an interface here:

Priorities.Add(new IList<SelectListItem>
{
    new SelectListItem { Text = "High", Value = "1"},
    new SelectListItem { Text = "Low", Value = "0"}
});

Instead try to instantiate it as something that implements IList and use AddRangewhich is meant for this kind of situation:

Priorities.AddRange(new List<SelectListItem>
{
  new SelectListItem { Text = "High", Value = "1"},
  new SelectListItem { Text = "Low", Value = "0"}
});

Upvotes: 1

Mate
Mate

Reputation: 5274

Try changing

Priorities = new List<SelectListItem>();

By

Priorities = new List<SelectListItem>() {
                new SelectListItem { Text = "High", Value = "1"},
                new SelectListItem { Text = "Low", Value = "0"}
            };

Or Cast and AddRange

 ((List<SelectListItem>)Priorities).AddRange(
                new List<SelectListItem>() {
                    new SelectListItem { Text = "High", Value = "1"},
                    new SelectListItem { Text = "Low", Value = "0"}
                }

            );

Other option using IEnumerable :

public IEnumerable<SelectListItem> Priorities { get; set; }
Priorities = new List<SelectListItem>();

Priorities = Priorities.Concat(new List<SelectListItem>() {
                new SelectListItem { Text = "High", Value = "1"},
                new SelectListItem { Text = "Low", Value = "0"}
                }
        );

Upvotes: 1

Related Questions