Javascript – How to i move items from one Listbox to another in ASP MVC 4

asp.netasp.net-mvc-4c++javascriptlistbox

How is it possible to move items from one Listbox to another Listbox in the same view without having to reload the entire page but just update the two listboxes in ASP MVC 4?

It is in order to have some selected music genres and then be able to submit those music genres to a webservice with a submit button.

The genres have an id which should not be shown and a name which should be shown.

I have tried to figure it out for the last 4 hours but i can't seem to get anything to work at all.

Edit: Solved moving items

I solved moving the items using jQuery.
I’ve added a reference to jquery.unobtrusive-ajax.js and added some methods to the view. The final view looks like this:

SelectGenre.cshtml
@model SelectGenreModel

<div id="genreDiv">
@Html.ListBoxFor(model => model.AvailableGenres, new MultiSelectList(Model.AvailableGenres, "Id", "Name"), new { size = "10" })

<input id="btnAddAll" type="button" value=" >> " onclick="addallItems();" />
<input id="btnAdd" type="button" value=" > " onclick="addItem();" />
<input id="btnRemove" type="button" value=" < "  onclick="removeItem();" />
<input id="btnRemoveAll"type="button" value=" << "  onclick="removeallItems();" />

@Html.ListBoxFor(model => model.ChosenGenres, new MultiSelectList(Model.ChosenGenres, "Id", "Name"), new { size = "10" })
</div>

<script type="text/javascript">
function addItem() {
    $("#AvailableGenres option:selected").appendTo("#ChosenGenres");
    $("#ChosenGenres option").attr("selected", false);
}
function addallItems() {
    $("#AvailableGenres option").appendTo("#ChosenGenres");
    $("#ChosenGenres option").attr("selected", false);
}
function removeItem() {
    $("#ChosenGenres option:selected").appendTo("#AvailableGenres");
    $("#AvailableGenres option").attr("selected", false);
}
function removeallItems() {
    $("#ChosenGenres option").appendTo("#AvailableGenres");
    $("#AvailableGenres option").attr("selected", false);
}
</script>

Edit: Continued in new question

I have asked with more information and more specific in this question
Get items from listbox in controller MVC ASP 4

Best Solution

I've made you a fiddle to give you an idea of how this could be achieved. You might find it useful.

Basically provided that you have 2 select elements (and presuming that you're using jQuery) you'd do something like:

$('#sourceItems').change(function () {
    $(this).find('option:selected').appendTo('#destinationItems');
});

And the corresponding html goes like:

<select id="sourceItems">
    <option>TestItem1</option>
    <option>TestItem2</option>
    // ...
</select>

<select id="destinationItems">
   // ... more options ...
</select>

Check out the fiddle for a working example. I hope this helps.