I have a list of items that I display to a user and allow them to select one or more of them by utilizing the jQuery UI Selectable interaction. In order to post the selected values back to the Controller I am including a hidden input field within each selectable item that I am setting via javascript on the selected event. Here is an example of how I have it setup
Model
public class ItemsViewModel
{
public List<Item> Items { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
Html
<ul id="Items">
<li>
<label>Item 1</label>
<input type="hidden" id="Items[0]_Id" name="Id" value="1" />
<input type="hidden" id="Items[0]_Selected" name="Items[0].Selected" class="is-selected" value="False" />
</li>
<li>
<label>Item 2</label>
<input type="hidden" id="Items[1]_Id" name="Items[1].Id" value="2" />
<input type="hidden" id="Items[1]_Selected" name="Items[1].Selected" class="is-selected" value="False" />
</li>
</ul>
JavaScript
$('#Items').selectable({
filter: 'li',
selected: function (event, ui) {
$(ui.selected).find('input.is-selected').val('True');
},
unselected: function (event, ui) {
$(ui.unselected).find('input.is-selected').val('False');
}
});
My first question, although this works, it isn't the prettiest solution. Does anyone have any better ways of posting the selectable items?
Second, I need to ensure that the user has selected at least one item from the list. Is it possible to hook up jQuery client side validation to ensure that the user has selected at least one item? I do have some thoughts about ways to implement this and I have no problem creating a custom validation attribute but I thought I would ask if it has already been done or the best way to of doing it before I threw something together.
Thanks