views:

30

answers:

1

Hi, I have a weird question. I have been writing a code to change the view by a <select>'s onchange like this:

<% 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(); %>

The selected value is numeric (i.e. 1,2,...).

Suddenly, I am able by changing the selected option to go from URL

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

to

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

.. And I really don't know why it works. Can anyone explain that to me please?

+2  A: 

The selected index of the drop down list is a 0-based index of the items in the list.

<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>

You are literally telling the select list, "When you change, grab the selected index of the value, and change the very last part of the URL to that index."

Jarrett Meyer
Ok, already helpful, but where do I say change only the last part of the URL? I thought changing the window.location.href property should change the whole URL.
Trimack
@Trimack it follows the same logic as `a href`. Unless you have a leading `http(s)://`, it will be treated as a relative location.
Jarrett Meyer