Jquery – ASP.NET MVC Listbox handling selected item events

asp.net-mvcjquery

I am using a HTML.ListBox within a view as such:

<%= Html.ListBox("projects", Model.Projects)  %>

This is populated with an IEnumerable<SelectListItem> in the model as such:

Projects = project.Select(a => new System.Web.Mvc.SelectListItem
        {
            Value = "foo",
            Text = a.project + "(" + a.count + ")",
            Selected = false
        });

        return Projects;

Which in turn is returned to the controller for passing into a strongly typed view.

My question is, how can I monitor for select item events? I need to be able to perform some action when the user makes a selection and/or de-selection.

Thanks.

Best Answer

If you're familiar with jQuery you can trap a change even and submit your FORM:

$('#projects').change(function () {
    $(this).parents('form').submit();
});

or you can use ajax to submit some data to an action

$('#projects').change(function () {
    $.ajax({
        type: 'POST',
        url: '<%=Url.Action("<action>", "<controller>")%>',
            data: { id: $('#projects').val() },
            dataType: 'json',
        complete: function(XMLHttpRequest, textStatus) {
            // Do something here.
            }
        });
});

UPDATE:

Since you're using jQuery Dropdown Check List you can trap the onItemClick even and call an action of your controller passing the value of the selected option and the status checked/non checked :

$("#projects").dropdownchecklist({
    emptyText: "select something",
    width: 150,
    onItemClick: function(checkbox, selector){
        var isChecked = checkbox.prop("checked");
        alert("element id: " + checkbox.prop("value"));

        $.ajax({
        type: 'POST',
        url: '<%=Url.Action("<action>", "<controller>")%>',
            data: { selecteId: checkbox.prop("value"), isChecked: isChecked },
            dataType: 'json',
        complete: function(XMLHttpRequest, textStatus) {
            // Do something here.
            }
        });
   }
});

You can have a look at this fiddle.