您可以通过为具有不同 id 的不同选择生成选项并为Url
属性呈现隐藏字段来实现。尝试以下:
<select id="url-list">
@foreach(var item in Model.individualPages)
{
<option value="@Model.Url">
@Model.Url
</option>
}
<option > custom... </option>
</select>
<input type="text" id="custom-url"/>
@Html.HiddenFor(e=>e.Url)
<script>
$(document).ready(function(){
$("select#url-list").change(function(){
var selectedItem =$("option:selected",$(this)),
selectedValue = selectedItem.val();
$("#url").val(selectedValue);
});
$("form").submit(function(){
var selectedItem = $("option:selected",$("select#url-list")),
selectedIndex = selectedItem.index(),
itemCount = $("option",$("select#url-list")).length;
if (selectedIndex == itemCount -1)
$("#url").val($("#custom-url").val());
});
});
</script>