TrevorGoodchild
TrevorGoodchild

Reputation: 1060

Passing array of checkbox values in MVC

I have a Razor view that contains a jQuery Datatables grid with a checkbox in each row. Each checkbox corresponds to a project, and the user selects which projects they wish to see in a printable page. I had to write employ some custom code to get all checkboxes across all pages, and then I'm passing those selected values to a hidden field on modal. The modal comes up when the user selects 'print', and the form is submitted to the controller from there. The controller then passes the value, as an array, to a service which returns the data to the view.

Here's the form on the modal:

@using (Html.BeginForm("GetPDFExport", "Project", FormMethod.Post, new { enctype = "multipart/form-data" , id = "PrintableProjectForm" }))
{
 <input type="hidden" name="projectId" id="projectId" value="">
 <Input type="submit" id="submitPrintableProject" value="Submit" />
}

and the code called to get the selected checkboxes into the hidden field on the modal:

$(document).on("click", "#printProject", function () {
 //code to get checkboxes on all pages
 var projectsGrid = $('#projectsGrid').dataTable();

 var selectedProjects = [];

 selectedProjects = projectsGrid.$('input[type="checkbox"]').serializeArray();

 var projects = [];

 $(selectedProjects).each(function (i, field) {
    projects.push(field.value);
 });

  $('#projectId').val(projects.toString());
});

and the controller signature:

public ActionResult GetProjects(Guid[] projectId)
{
//service call that returns projects
}

My problem is that I can't get the values from the hidden field to the controller, the controller is always showing null. I was originally trying to do this with an AJAX call, which worked, but we're actually redirecting to the print page which was causing other problems. This seems like it should be simple, hoping someone can help me out.

EDIT: Doing a lot of research, everything says to use an AJAX call but I'm not staying on the same page. I need to post the data to the controller, get the projects from the server, and then serve up the view with the corresponding model. The only reason I'm using jQuery at all is to correctly get all of the checkbox values. This can't possibly be this unique of a scenario, am I crazy here?

Upvotes: 0

Views: 1229

Answers (1)

Rafael Justiniano
Rafael Justiniano

Reputation: 26

You can remove that hidden input, and try something like this:

$(document).on("click", "#printProject", function () {
     //code to get checkboxes on all pages
     var projectsGrid = $('#projectsGrid').dataTable();

     var form = $('#PrintableProjectForm');

     var selectedProjects = [];

     selectedProjects = projectsGrid.$('input[type="checkbox"]').serializeArray();

     $(selectedProjects).each(function (i, field) {
         form.append($('<input />').attr('name', 'projectId').attr('hidden', 'hidden').val(field));
     });

});

Upvotes: 1

Related Questions