mardi 25 juillet 2017

How to pass values of checkboxes from JavaScript/view to controller in MVC?

I am working on a form which enables a maximum of 11 football players to be selected from a list using checkboxes. They are separated and named based on their playing position.

            @if (item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 1).FirstOrDefault())
            {
                @Html.CheckBox("goalkeepers", false)
            }

            @if (item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 2).FirstOrDefault())
            {
                @Html.CheckBox("defenders", false)
            }

            @if (item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 3).FirstOrDefault())
            {
                @Html.CheckBox("midfielders", false)
            }

            @if (item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 4).FirstOrDefault())
            {
                @Html.CheckBox("forwards", false)
            }

I am using the following piece of JavaScript to display each of the selected values in order inside a pop-up box when a button is clicked.

    $('#button').click(function () {
    alert($('input[type="checkbox"]:checked').eq(0).val()); // 1st
    alert($('input[type="checkbox"]:checked').eq(1).val()); // 2nd
    alert($('input[type="checkbox"]:checked').eq(2).val()); // 3rd
    alert($('input[type="checkbox"]:checked').eq(3).val()); // 4th
    alert($('input[type="checkbox"]:checked').eq(4).val()); // 5th
    alert($('input[type="checkbox"]:checked').eq(5).val()); // 6th
    alert($('input[type="checkbox"]:checked').eq(6).val()); // 7th
    alert($('input[type="checkbox"]:checked').eq(7).val()); // 8th
    alert($('input[type="checkbox"]:checked').eq(8).val()); // 9th
    alert($('input[type="checkbox"]:checked').eq(9).val()); // 10th
    alert($('input[type="checkbox"]:checked').eq(10).val()); // 11th
});

However, what I really want to do with these values is pass them through to the controller so that I can record them in the database. These checkboxes are placed within a partial view and are not part of this particular model which is why it's not so straightforward (at least as far as I can see).

Basically, everything is working as I would like apart from not being able to record the IDs of each player that has been selected. I am thinking that there must be a way of doing this - either by expanding on what I have done slightly or by using a different approach.

Ideally, I would like to record each of the eleven values separately rather than as an array.




Aucun commentaire:

Enregistrer un commentaire