简体   繁体   English

如何通过aspx视图内的foreach循环在下拉列表中默认设置所选选项

[英]How to set selected option by default in a dropdown list via a foreach loop inside an aspx view

in an mvc 1 aspx view I'm adding a dropdown list for countries, sorted by alphabetical order using a foreach loop: 在mvc 1 aspx视图中,我添加了一个国家/地区的下拉列表,使用foreach循环按字母顺序排序:

<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. 但这只是最后添加了另一个选项,我总是可以从列表中删除UK条目,但仍然会破坏排序。

I've been trying to insert an if statement inside but I can't figure it out so I would appreciate any heads up. 我一直在尝试在其中插入if语句,但无法弄清楚,因此请多加注意。

Thanks!!! 谢谢!!!

You could have an if statement in the foreach loop which optionally renders one of the two option elements based on whether the item is selected or not. 您可能在foreach循环中有一个if语句,该语句根据是否option了该项,有option地呈现两个option元素之一。

You could also conditionally render the selected attribute only if the option is selected, that might make the code a little less readable, but the duplication would be limited. 您还可以仅在selected了选项的情况下有条件地呈现selected属性,这可能会使代码的可读性降低,但是复制将受到限制。

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. 最后,我可能会创建一个渲染该选项的帮助程序,并且可以将一个标志传递给它,如果不包括选择的内容,则循环将根据正确的参数调用该帮助程序,具体取决于是否是否应该选择它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM