-1

I have a "to do list" where the tasks (assignments) are stored as records in a database. One of the elements in the Assignment model is Complete. The page outputs all of the values in the Assignments (List<Assignment>) table using a for loop, along with a checkbox on the end.

@using (var ctx = new AssignmentContext())
        {
            var assignmentList = ctx.Assignments.ToList();
            foreach (Assignment assignment in assignmentList)
                <tr name ="@assignment.AssignmentId">
                    <td>@assignment.CourseName</td>
                    <td>@assignment.AssignmentName</td>
                    <td>@assignment.DueDate</td>
                    <td>@assignment.Value</td>
                    <td>@Html.CheckBox()</td>
                </tr>
        }

I want to change the state of the bool Assignment.Complete in the database on the click of the checkbox. I am pretty new to web development and the mixing of HTML and C# is what confuses me here. How do I have a onClick call a controller function and when I do, how do I pass it the specific row after the for loop has already ran. Do I NEED JS here?

  • Please provide the sample code (or minimal code) to reproduce the issue. – xoxo Oct 04 '18 at 05:26
  • 1
    Suggest you read [Pass List of Checkboxes into View and Pull out IEnumerable](https://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416), but if you do want to do this one at a time, then using ajax to call a server method would be an option. –  Oct 04 '18 at 05:26

1 Answers1

2

try it: CsHtml:

  @using (var ctx = new AssignmentContext())
            {
                var assignmentList = ctx.Assignments.ToList();
                foreach (Assignment assignment in assignmentList)
                    <tr name ="@assignment.AssignmentId">
                        <td>@assignment.CourseName</td>
                        <td>@assignment.AssignmentName</td>
                        <td>@assignment.DueDate</td>
                        <td>@assignment.Value</td>
                        <td>@Html.CheckBox(assignment.AssignmentId, assignment.Complete, new {@id= assignment.AssignmentId,onclick= "complete($(this))" })</td>
                    </tr>
            }

Java Script:

<script>
    function complete(selector) {
        var assignmentId = selector.attr('id');

        $.get('/Assignment/Complete', { id: assignmentId, checked: selector.checked}, function() {
          alert('successfull')  
        })

    }

</script>

Controller:

public async Task<JsonResult> Complete(int id,bool checked)
        {

            @using(var ctx = new AssignmentContext())
            {
            var assignment =   ctx.Assignments.Find(id);
                assignment.Complete = checked;
                ctx.SaveChanges();


            }
            return Json(new { isSuccess =true }, JsonRequestBehavior.AllowGet);
        }
Mehran Hafizi
  • 2,392
  • 2
  • 12
  • 14