簡體   English   中英

mvc3 dropdownlist設置從模型中選擇的值

[英]mvc3 dropdownlist setting the selected value from model

我在.aspx頁中創建一個選擇列表。

<label for="AccessType" class="required"><span class="required">*</span><%=Html.Resource("accessType")%>:</label>
                <select id="AccessType" name="AccessType">
                <% foreach (var item in Enum.GetValues(typeof(Security.AccessType)))
                {%> 
                <option value="<%=(int)item%>"><%=item%> </option> 
                <%}%>
                </select><br />

現在,每次我加載頁面時,它都會選擇第一個值作為默認值,因為我希望選擇模型中存在的值。

我在代碼中對下拉列表進行枚舉。 Security.AccessType是一個枚舉,而不是模型。 因此,每次頁面加載時,都會將下拉列表的選定值顯示為第一個枚舉

我希望所選的項目是Model.AccessType ...

我知道這是一個非常基本的問題,但仍然有幫助嗎?

您可以為要默認設置的選項提供“選定”屬性,例如:

<option value="apple" selected="selected">apple</option> 

如果要動態選擇一個選項,則可以使用javascript進行選擇。 例如:

var el = document.getElementById("AccessType");
el.selectedIndex = yourIndex; //index of the option you want to select
//or
el.value = "yourValue"; //value of the option you want to select

我使用了Followig並得到了結果。

$('#ddlAccessType')。val($(“#ddlAccessType選項:contains('” + $('#AccessTypeValue')。val()+“')”)。val());

這是首先獲取AccessType值,然后在下拉列表中檢查其索引,然后將所選索引設置為找到的索引。

有點古怪,但對我來說很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM