I am trying to migrate my ASP.NET Webforms project into ASP.NET MVC (for learning purposes). I need to get the value of the selected index from a listbox in ASP.NET MVC and use this index for sorting strings in a textbox. It was extremely simple in my webforms project:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
Height="166px" Width="198px"
BackColor="Black" Font-Bold="True" ForeColor="White" Font-Size="Small"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Height="149px" Width="286px"
TextMode="MultiLine" OnTextChanged="TextBox1_TextChanged"
AutoPostBack="True" Font-Bold="True" ForeColor="#006600">
</asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ListBox1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
And the code behind was:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
...
i = ListBox1.SelectedIndex;
TextBox1.Text += ....// here is a string sorted based on the selected index i);
...
}
But I have not found a way to receive the selected index in ASP.NET MVC despite a two-day search at IT forums.
I populated the listbox in a view in this way:
@Html.ListBoxFor(x => x.SelectedIndexes, new SelectList(Model.Entries,
"Value", "Text"), new { id = "ListBox1", onchange =
"selectedIndexChanged()", style = "width:198px; height:166px; color:white;
background:black; font-weight:bold" })
A list of entries was created in a model and sent via a controller to the view. It works and the listbox is populated. But in ASP.NET MVC, there seems to be nothing like ListBox1.SelectedIndex. Is it possible to receive the value on the client side (JavaScript's statement: document.getElementById("ListBox1").selectedIndex ), but there seems to be no way to transfer this value to the server side.
Does anybody know how to extract the value of the selected index and transfer it into the model?
$('#SelectedIndexes').change(function() { var selected = $(this).val(); $.post(your url, { id: selected }. function(data) { do somethng with the data you return }); });onchange = "selectedIndexChanged()"(use Unobtrusive Javascritpt). And replace yourstyle attribute with a class. And it already looks likeModel.Entries` isIEnumerable<SelectList>so creating another identical one usingnew SelectList(..)in the view is pointless.