0

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")
2
  • 1
    Change Priorities.Add(new IList<SelectListItem> {.. to Priorities.Add(new SelectListItem { Text = "High", Value="1" }); Commented Nov 25, 2014 at 22:41
  • I am trying to add multiple items at a time. Commented Nov 25, 2014 at 22:46

2 Answers 2

1

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

Comments

1

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

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.