代码之家  ›  专栏  ›  技术社区  ›  Trimack

为什么这段代码会根据需要更改位置

  •  0
  • Trimack  · 技术社区  · 15 年前

    我有个奇怪的问题。我一直在写一个代码来更改视图 <select> onchange 这样地:

    <% Html.BeginForm(); %>
    <label for="id" >Automat:</label>
    <%= Html.DropDownList("id", Model as SelectList, new { @onchange = "window.location.href = document.getElementById('id').options[document.getElementById('id').selectedIndex].value;" })%>
    <% Html.EndForm(); %>
    

    所选值为数字(即1,2,…)。

    突然间,我可以通过更改所选选项从URL转到

    http://localhost:58296/Content/ViewContent/2
    

    http://localhost:58296/Content/ViewContent/3
    

    …我真的不知道为什么会这样。有人能给我解释一下吗?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Jarrett Meyer    15 年前

    下拉列表的所选索引是列表中项目的基于0的索引。

    <select>
      <option>Some Option 1</option> <!-- I have index 0 -->
      <option>Some Option 2</option> <!-- I have index 1 -->
      <option>Some Option 3</option> <!-- I have index 2 -->
    </select>
    

    您实际上是在告诉选择列表,“当您更改时,获取所选值的索引,并将URL的最后一部分更改为该索引。”