0

I have following ViewModel containing "NumberOfAdults" fields.

public class SearchView
{
    public int NumberOfAdults { get; set; }
    // More fields...

}

Assuming it will have some value (lets say 5) populated from some configuration file and I have a strongly typed View. What is the best way to populate a dropdown containing text and values of 1,2,3,4,5 without hard coding <Select...><Option value="1">1</Option></Select>? Is there a MVC way of doing it?

1 Answer 1

1

I wouldn't be surprised if there's a helper that I'm not thinking of that could build the SelectList more elegantly, but this works.

    <%  
        // Build a list of SelectListItem from 1 to N
        List<SelectListItem> options = new List<SelectListItem>();
        for (int i = 1; i <= Model.NumberOfAdults; i++)
        {
            string stringValue = i.ToString();
            SelectListItem item = new SelectListItem() { Value = stringValue, Text = stringValue };
            options.Add(item);
        }
    %>

    <%= Html.DropDownList("yourName", options) %>

This renders:

<select id="yourName" name="yourName">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
Sign up to request clarification or add additional context in comments.

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.