0

Just wondering if anyone can help with this problem. I have a viewmodel which populates a dropdownlist. I was just wondering if it's possible to change my code below so that I can use a for loop to populate the list.

ViewModel

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

Controller

numberOfAdults = new[]
                {  
                    new SelectListItem {Value = "1", Text = "1"},
                    new SelectListItem {Value = "2", Text = "2"},
                    new SelectListItem {Value = "3", Text = "3"},
                    new SelectListItem {Value = "4", Text = "4"},
                    new SelectListItem {Value = "5", Text = "5"},
                    new SelectListItem {Value = "6", Text = "6"},
                    new SelectListItem {Value = "7", Text = "7"},
                    new SelectListItem {Value = "8", Text = "8"},
                    new SelectListItem {Value = "9", Text = "9"},
                    new SelectListItem {Value = "10", Text = "10"}
                }

View

@Html.DropDownListFor(x => x.selectedAdultValue, new SelectList(Model.numberOfAdults, "Value", "Text"), null, new {@id="NumerOfAdults" })

Something like the following is what I would like, but not sure where to put it in model or controller.

for(int i = 0; i < 10; i++)
{
    i;
}

1 Answer 1

5

It could be as simple as:

numberOfAdults = Enumerable.Range(1, 10).Select(x => new SelectListItem
{
    Value = x.ToString(),
    Text = x.ToString()
});

or if you really want to use a for loop (I don't see why would you want that but anyway):

var result = new List<SelectListItem>();
for(int i = 1; i <= 10; i++)
{
    result.Add(new SelectListItem { 
        Value = x.ToString(),
        Text = x.ToString() 
    });
}
numberOfAdults = result.ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Darin, the reason I was going to use for loop was because I did not know you could use Enumerable.Range like your example

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.