[英]mvc3 dropdownlist setting the selected value from model
I am creating a select list in my .aspx page. 我在.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 />
Now every time I load the page it is selecting the first value as default, where as I want the value present in model to be the selected. 现在,每次我加载页面时,它都会选择第一个值作为默认值,因为我希望选择模型中存在的值。
I am biniding the dropdown to a enum in my code. 我在代码中对下拉列表进行枚举。 Security.AccessType is a enum and not a model.
Security.AccessType是一个枚举,而不是模型。 so every time the page loads it shows the selected value of the dropdown as first enum
因此,每次页面加载时,都会将下拉列表的选定值显示为第一个枚举
I want the selected item to be say Model.AccessType... 我希望所选的项目是Model.AccessType ...
I know its a very basic question but still any help? 我知道这是一个非常基本的问题,但仍然有帮助吗?
You can give the option which you want to be default a "selected" attribute, like: 您可以为要默认设置的选项提供“选定”属性,例如:
<option value="apple" selected="selected">apple</option>
If you want to select an option dynamically, you can do it by javascript. 如果要动态选择一个选项,则可以使用javascript进行选择。 Eg:
例如:
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
I used the followig and got the result.. 我使用了Followig并得到了结果。
$('#ddlAccessType').val($("#ddlAccessType option:contains('" + $('#AccessTypeValue').val() + "')").val()); $('#ddlAccessType')。val($(“#ddlAccessType选项:contains('” + $('#AccessTypeValue')。val()+“')”)。val());
This is first getting the AccessType value then checking for its index in the dropdown list and then setting the selected index to the index found out. 这是首先获取AccessType值,然后在下拉列表中检查其索引,然后将所选索引设置为找到的索引。
A bit bizzare, but worked fine for me.. 有点古怪,但对我来说很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.