1

我对 MVC 相当陌生,但对 ASP.Net 有一些不错的经验。

我试图调查我的下拉列表中可能有一个自定义选项。下面是我的下拉列表和我的编辑器。显然,在提交页面时,选择的值和输入的数据都不会被存储。我正在查看是否允许在下拉列表中使用“自定义”选项,是否可以存储在编辑器中输入的值而不是下拉列表选择?除非选择是下拉列表的自定义值,否则甚至可能不显示编辑器。

     @Html.DropDownListFor(model => model.Url, Model.individualPages)
     @Html.EditorFor(model => model.Url)
4

1 回答 1

2

您可以通过为具有不同 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>
于 2013-02-28T20:12:35.423 回答