Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a list of selected checkboxes from view to controller

I have been trying to work out how I can get the list of selected checkboxes to work using an ActionLink. I think I need to do something clientside with JavaScript but cannot find the relevant code.

The following code works perfectly using a submit button, posting back the selected id's as an array of id's, but I need to have this on a page with other buttons.

// the view 
@foreach (var station in Stations)
{
   <input type="checkbox" name="selected" value="@station.StationId" /> 
}    
<input type="submit" value="Save" />

//Controller stub
public ActionResult Action(string [] selected) 

I have been stuck on this for hours, so maybe I am looking at this the wrong way.

PS. My first post after many many hours reading and learning here.

like image 594
tr3v Avatar asked Dec 04 '12 03:12

tr3v


1 Answers

SomeButtons or links to post checkboxlist values

<a href="#" id="someButton">Post</a>
//or buttons, helpers and any elements to trigger ajax post...

CheckboxList:

<div id="MyDiv">
    @foreach (var station in Stations)
    {
        <input type="checkbox" name="selected" value="@station.StationId" /> 
    }  
</div>

Scripts:

$(document).ready(function() {
    $('#someButton').click(function() {
        var list = [];
        $('#MyDiv input:checked').each(function() {
            list.push(this.name);
        });
        // now names contains all of the names of checked checkboxes
        // do something with it for excamle post with ajax
        $.ajax({
            url: '@Url.Action("Action","Contoller")',
            type: 'POST',
            data: { Parameters: list},
            success: function (result) {
                alert("success")!
            },
            error: function (result) {
                alert("error!");
            }
        });   //end ajax
    });
});

Controller:

public ActionResult Action(string [] Parameters) 

if I got it right :)

like image 125
AliRıza Adıyahşi Avatar answered Sep 18 '22 09:09

AliRıza Adıyahşi