in an mvc 1 aspx view I’m adding a dropdown list for countries, sorted by alphabetical order using a foreach loop:
<div class="row">
<label>Country</label>
<select name="registration-country" id="registration-country">
<%foreach (var country in countryList) { %>
<option value ="<%=country.CountryGUID %>" ><%= country.CountryName %></option>
<% } %>
</select>
</div>
The only way I can think of is:
<div class="row">
<label>Country</label>
<select name="registration-country" id="registration-country">
<%foreach (var country in countryList) { %>
<option value ="<%=country.CountryGUID %>" se><%= country.CountryName %></option>
<% } %>
<option selected="selected" value="79118727-F7AC-4E38-BB7D-DC31A66E111F">United Kingdom</option>--%>
</select>
</div>
But this just adds another option at the end, I could always remove the UK entry in the list, but still would ruin the sorting.
I’ve been trying to insert an if statement inside but I can’t figure it out so I would appreciate any heads up.
Thanks!!!
You could have an
ifstatement in theforeachloop which optionally renders one of the twooptionelements based on whether the item is selected or not.You could also conditionally render the
selectedattribute only if the option is selected, that might make the code a little less readable, but the duplication would be limited.Finally, and what I would probably go with is to create a helper which renders the option and you can pass a flag to it if selected should be included or not, then your loop will just be calling the helper with the correct arguments depending on whether it should be selected or not.