present a multi select list as togglebuttons in asp mvc
I'm creating a form where the user will select n days from a list of week days.
example - think of a multi select list with the following values: Monday, Tuesday, Wednesday, Thursday, Friday and the user will select Tuesday and Thursday.
So, on my action I create a select list with the name of the week days and an Id for each of them and pass it to the View inside the ViewData.
ViewData["WeekDays"] = new SelectList(weeklist, "Id", "Name");
on my Action i have something like this to present the week days:
<% using (Html.BeginForm()) { %>
<% foreac开发者_如何转开发h (var day in (SelectList)ViewData["WeekDays"]) {%>
<a id="<%= day.Value %>" title="<%= day.Text %>" class="toggleOff">
<%= day.Text %>
</a>
<% } %>
<input type="submit" value="<%= Html.Resource("Continue") %>" />
<% } %>
and the page has the following script to create the look and fell of a toggle button:
$(document).ready(function () {
$('a.toggleOff').click(function () {
$(this).toggleClass("toggleOn");
});
$('a.toggleOn').click(function () {
$(this).toggleClass("toggleOff");
});
}
with some css magic for the classes toggleOn and toggleOff this will present a toggle button list to the user.
My problem is how to post back to the controller the days selected by the user?
Well, I was able to found the solution by myself.
On the View I replaced the tag with two inputs, a button and a hidden input.
<% foreach (SelectListItem day in (SelectList)ViewData["WeekDays"]) {%>
<input id="SelectedDays_<%= day.Value %>_" name="SelectedDays[<%= day.Value %>]" type="button" value="<%= day.Text %>" class="toggleOff" />
<input id="SelectedDays_<%= day.Value %>_Hidden" name="SelectedDays[<%= day.Value %>]" type="hidden" value="false" />
<% } %>
And used the jquery to set the the hidden input value when someone press the button:
$('input.toggleOff').click(function () {
var id = '#' + $(this).attr('id') + 'Hidden';
$(this).toggleClass("toggleOn");
if ($(id).attr('value') == "false") {
$(id).attr('value', 'true');
} else {
$(id).attr('value', 'false');
}
});
精彩评论