简体   繁体   中英

How do I save List of Checkboxes with value as Id to a database?

I have lists of courses from different table displaying on the same view as shown below在此处输入图像描述

I want a user to select the courses he wants to register by selecting the checkboxes. How do I get the Id's of the courses selected, then pass to the controller to save to another table.

I have my HTML code as this

    @model FlexSchool.Data.Models.ClassModelIndex

                    <tbody>
                                            @foreach (var item in Model.AdmInstAssignCourses.Where(m => m.IsCompulsory == true))
                                            {
                                                <tr>
                                                    <td>
                                                        <input type="checkbox" class="checkBox" name="check" value="@item.AdmInstCourses.CourseId" />
                                                    </td>
                                                    <td>  @Html.DisplayFor(modelItem => item.AdmInstCourses.CourseCode) </td>
                                                    <td> @Html.DisplayFor(modelItem => item.AdmInstCourses.CourseName)</td>
                                                    <td> @Html.DisplayFor(modelItem => item.AdmInstCourses.Units)</td>

                                                </tr>
                                            }
                                        </tbody>

Where ClassModelIndex is a class of IEnumerable Classes which i used in displaying different tables to list.

My button goes thus <input type="submit" value="Register Courses" id="register" class="btn btn-rose" />

My script looks like this

    <script>
    $(document).ready(function () {

        $("#register").click(function () {
            var selectedIDs = [];
            $('input[type=checkbox]').each(function () {
                selectedIDs.push($(this).val());
            });
            $.ajax({

                url = "/Course/RegisterCourse",
                type = "POST",
                data = JSON.stringify({ courseIDs: selectedIDs }),
                contentType = "application/json; charset=utf-8",
                dataType = "json",
                success = function (data) {
                    alert(data);
                },
                error = function () {
                    alert("Error while registering courses!");
                },
            });
        });



</script>

My Controller is

    [HttpPost]
        public async Task<ActionResult> RegisterCourse(List<string> courseIDs)
        {

            var user = HttpContext.Session.GetString(InstName);
            if (user == null)
            {
                return RedirectToAction("Login", "Account");
            }

            foreach (string courseID in courseIDs)
            {
                AdmInstCourses obj = await _context.AdmInstCourses.FindAsync(courseID);
                var mycourses = new CourseRegModel { CourseCode = obj.CourseCode, CourseTitle = obj.CourseName, CourseUnit = obj.Units};
                _context.Add(mycourses);

            }
            await _context.SaveChangesAsync();
            return RedirectToAction("MyCourses", "Course");
        }

But when I run the code in debugging mode, I notice my courseIDs is not getting any list of string as Id. So it is either the script is not getting the checked boxes to pass to the controller.

What exactly am I doing wrong?

The issue is with the JavaScript Code. You have missed :checked .Use following code to get all checked values. And make sure no space between input[type="checkbox"] and :checked .

var selectedIDs = [];
$('input[type="checkbox"]:checked').each(function () {
    // looping through each checkbox and storing values in array for checked ones.
    selectedIDs .push($(this).val());
});

Please try below Ajax code:

var selectedIDs = [];
$('input[type=checkbox]').each(function () {
    selectedIDs.push($(this).val());
});

$.ajax({
        url : '/Course/RegisterCourse',
        type : "POST",
        data: JSON.stringify(selectedIDs),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function (data) {
            alert(data);
        },
        error : function () {
            alert("Error while registering courses!");
        }
    });

Directly pass json string( JSON.stringify(selectedIDs) ) to server side, and in the controller method, use [FromBody] to get the values:

[HttpPost]
public async Task<ActionResult> RegisterCourse([FromBody]List<string> courseIDs)
{


}

First and foremost you can't put ids in checkbox value, because the value of checkbox can has true or false.

Try to use html.HiddenFieldFor(model => model.YourModel[i]) and replace foreach by for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM