0

I'm a new mvc developper, I make a list in my controller, my view show this list and for each row i have a button for a modal view.I want to pass the data of the ViewBag in my list according for each row in my modal.

This is my modal html:

    <div class="modal" id="addBadgetoStudentModal-@item.ID" tabindex="-1" role="dialog" aria-hidden="true">
       <div class="modal-dialog modal-lg animated bounceInDown">
           <div class="modal-content">
               @using (Html.BeginForm("AddBadgeToStudent", "Badges", new { ID = item.ID }, FormMethod.Post))
               {
                   @Html.AntiForgeryToken()
                   @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                   <div class="modal-header">
                       <h4 class="modal-title">Badges</h4>
                       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                   </div>
                   <div class="modal-body">
                       <div class="form-group">
                           <div class="">
                               <div class="row">
                                   @if (ViewBag.Badges != null)
                                   {
                                       for (var i = 0; i < ViewBag.Badges.Count; i++)
                                       {
                                           <div class="col-lg-3 col-sm-6 col-md-4">
                                               <div class="team-member ">
                                                   <div class="row margin-0">
                                                       <div class="team-info" style="text-align:center; border: 1.2pt solid #1874BF;">
                                                           <img src="@ViewBag.Badges[i].ImageURL" style="width:80%;" class="img-fluid" />
                                                       </div>
                                                       <div class="team-info" style="text-align:center; width:100%;">
                                                           @ViewBag.Badges[i].Label
                                                           <br />
                                                           <input id="Badge_@ViewBag.Badges[i].ID" class="checkBoxBadgeClass" type="checkbox" />
                                                        </div>
                                                   </div>
                                               </div>
                                           </div>
                                       }
                                   }
                               </div>
                           </div>
                       </div>
                   </div>
                   <div class="modal-footer">
                       <a href="#" id="AssignBadges" class="btn btn-default" input type="submit" name="Badges"><i class="fa fa-plus-circle"></i>&nbsp;@Resource.Add</a>
                   </div>
               }
           </div>
       </div>
   </div>
                                        <a class="fa fa-pencil-alt" data-toggle="modal" href="#addBadgetoStudentModal-@item.ID" onclick="btnModal()"></a>

This is my List Html View:

                @foreach (var item in Model)
                {
                    <tr id="@item.ID">
                        <td style="text-align:center; width:5%;">
                            @Html.DisplayFor(modelItem => item.ID)
                        </td>
                        <td style="text-align: center; width:25%;">
                            @item.FullName
                        </td>
                        <td style="width:450px;">
                                @for (var i = 0; i < item.BadgesAssigned.Count; i++)
                                {
                                <img src="@item.BadgesAssigned[i].ImageUrl" width="50" title="@item.BadgesAssigned[i].Name" style="float:left;" />
                                }
                                <input type="hidden" id="studentBadges_@item.ID" value="@String.Join(",", item.BadgesAssigned.Select(x => x.ID.ToString()))"/>
                        </td>   
}

and this my controller to get my student list and in another table get the badge assigned to a student, so in the list view the student can have 20 badges/25:

    public ActionResult BadgeManagement(int? CohortId, int? id)
    {
        ViewBag.CohortId = db.Cohorts.Select(p => new SelectListItem
        {
            Text = p.Name,
            Value = p.ID.ToString()
        });

        if (CohortId != null ? CohortId > 0 : false)
        {
            var cs = db.CohortSubscriptions.Where(student => student.CohortId == CohortId).Include(c => c.Cohorts).Include(c => c.Registrations);
            List<BadgesByStudentViewModel> badgesByStudentList = new List<BadgesByStudentViewModel>();
            foreach (var student in cs) {
                badgesByStudentList.Add(new BadgesByStudentViewModel
                {
                    ID = student.ID,
                    FullName = student.Registrations.FullName,
                    BadgesAssigned = db.Enrolled_Students_Badges.Where(x => x.CohortSubscriptionId == student.ID).Select(x => new BadgesAssigned
                    {
                        ID = x.ID,
                        Name = x.Label,
                        ImageUrl = x.ImageURL
                    }).ToList()
                });
            }
            ViewBag.Badges = db.Badges.ToList();
            return View(badgesByStudentList.ToList());
        }

        return View(new List<BadgesByStudentViewModel>());
    }

1 Answers1

0

I found my solution

This is my html:

                    <tbody>
                        @foreach (var item in Model)
                        {
                            <tr id="@item.ID">
                                <td style="text-align:center; width:5%;">
                                    @Html.DisplayFor(modelItem => item.ID)
                                </td>
                                <td style="text-align: center; width:25%;">
                                    @item.FullName
                                </td>
                                <td style="width:450px;">
                                    @for (var i = 0; i < item.BadgesAssigned.Count; i++)
                                    {
                                        <img src="@item.BadgesAssigned[i].ImageUrl" width="50" title="@item.BadgesAssigned[i].Name" style="float:left;" />
                                    }
                                </td>
                                <td style="text-align:center; width:5%;">

                                    <button style="border:none;background: transparent;" data-studentid="@item.ID" data-studentname="@item.FullName" data-badges="@String.Join(",", item.BadgesAssigned.Select(x => x.ID.ToString()))" data-toggle="modal" data-target="#addBadgetoStudentModal" class="modalLink"><i class="fa fa-pencil-alt"></i></button>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
                <div class="modal" id="addBadgetoStudentModal" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog modal-lg animated bounceInDown">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">Badges</h4>
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            </div>
                            <div class="modal-body">

                                <div class="form-group">
                                    <div class="">
                                        <u>@Resource.AddBadgeToStudent:</u>
                                        <br />
                                        <br />
                                        <div class="row">
                                            @if (ViewBag.Badges != null)
                                            {
                                                for (var i = 0; i < ViewBag.Badges.Count; i++)
                                                {
                                                    <div class="col-lg-3 col-sm-6 col-md-4">
                                                        <div class="team-member ">
                                                            <div class="row margin-0">
                                                                <div class="team-info" style="text-align:center; border: 1.2pt solid #1874BF;">
                                                                    <img src="@ViewBag.Badges[i].ImageURL" style="width:80%;" class="img-fluid" />
                                                                </div>
                                                                <div class="team-info" style="text-align:center; width:100%;">
                                                                    @ViewBag.Badges[i].Label
                                                                    <br />
                                                                    <input id="Badge_@ViewBag.Badges[i].ID" data-badgeid="@ViewBag.Badges[i].ID" data-label="@ViewBag.Badges[i].Label" class="checkBoxBadgeClass" type="checkbox" />
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                }
                                            }
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <a href="#" id="AssignBadges" class="btn btn-default" input type="submit" name="Badges"><i class="fa fa-plus-circle"></i>&nbsp;@Resource.Edit</a>
                            </div>
                        </div>
                    </div>
                </div>

and this is my jquery:

    currentStudentId = null;

    currentAssignedBadge = [];
    $('#BadgeAssignmentTable').dataTable({
        responsive: true,
        aLengthMenu: [
            [10, 25, 50, 100, -1],
            [10, 25, 50, 100, "All"]
        ]
    });

    $(".modalLink").on("click", function () {
        var $pencil = $(this);
        var studentId = $pencil.data('studentid');
        var badges = $pencil.data('badges');
        var studentName = $pencil.data("studentname");
        PrepareBadgesModal(studentId, badges.split(","), studentName);
    });

    PrepareBadgesModal = function (studentId, assignedBadges, studentName) {
        currentStudentId = studentId;
        console.log(assignedBadges);
        currentAssignedBadge = [];
        $.each(assignedBadges, function (k, v) { return currentAssignedBadge.push(parseInt(v, 10)); });
        $.each(assignedBadges, function (k, v) {
            var $badge = $("#Badge_" + v);
            $badge.prop("checked", true);
            var label = $badge.data("label");
            $badge.on("click", function (event) {
                var res = ConfirmRemoveBadge($(this), label, studentName);
                event.stopPropagation();
            });
        });
    }

    ConfirmRemoveBadge = function ($badge, label, studentName) {
        var txt = "ATTENTION\r\rÊtes-vous certain de vouloir retirer le badge \"" + label + "\" à " + studentName + "?";
        var r = confirm(txt);
        if (r == true) {
            $badge.prop("checked", false);
            $badge.unbind("click");
        } else {
            $badge.prop("checked", true);
        }
    }

    $("#AssignBadges").click(function () {
        ModifyBadgesAction();
    });

    ModifyBadgesAction = function (badgeList) {
        var selBadgeLst = $('input[id^=Badge_]:checked').map(function (k, v) { return parseInt($(v).data('badgeid'), 10); });

        //TODO: Close the modal
        var removedLst = $.grep(currentAssignedBadge, function (v, k) {
            return $.grep(selBadgeLst, function (vv, kk) {
                return v == vv;
            }).length == 0;
        });

        var AddedList = $.grep(selBadgeLst, function (v, k) {
            return $.grep(currentAssignedBadge, function (vv, kk) {
                return v == vv;
            }).length == 0;
        });

        var jsonData = JSON.stringify({ studentId : currentStudentId, AddedList: AddedList, removedLst: removedLst });
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Badges/ModifyBadgesAction',
            data: jsonData,
            success: function (data, textStatus, jqXHR) {
                //console.log(data, textStatus, jqXHR);
                if (data.code == 0) {
                    ApplyBadgeActionSuccess(data);
                }
                else {
                    ApplyBadgeActionError(data);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                ApplyBadgeActionError({ code: jqXHR.status, message: "Technical Error", data: [{ jqXHR: jqXHR, error: errorThrown }] });
            }
        });
    };

    ApplyBadgeActionSuccess = function (data) {
        alert(data.message);
        window.location.reload(true);
    }
    ApplyBadgeActionError = function (data) {
        alert(data.message);
    }