简体   繁体   English

如何将值为 Id 的复选框列表保存到数据库中?

[英]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.我希望用户通过选中复选框来注册他想要注册的课程 select。 How do I get the Id's of the courses selected, then pass to the controller to save to another table.如何获取所选课程的 ID,然后传递给 controller 以保存到另一个表。

I have my HTML code as this我有我的 HTML 代码

    @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.其中ClassModelIndexIEnumerable类的 class,我用于显示要列出的不同表。

My button goes thus <input type="submit" value="Register Courses" id="register" class="btn btn-rose" />我的按钮因此<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我的Controller

    [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.但是当我在调试模式下运行代码时,我注意到我的courseIDs没有将任何字符串列表作为 Id。 So it is either the script is not getting the checked boxes to pass to the controller.因此,要么script没有将复选框传递给 controller。

What exactly am I doing wrong?我到底做错了什么?

The issue is with the JavaScript Code.问题在于 JavaScript 代码。 You have missed :checked .Use following code to get all checked values.您错过了:checked 。使用以下代码获取所有检查值。 And make sure no space between input[type="checkbox"] and :checked .并确保input[type="checkbox"]: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:请尝试以下 Ajax 代码:

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:直接将 json 字符串( JSON.stringify(selectedIDs) )传递给服务器端,并在 controller 方法中,使用[FromBody]获取值

[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.首先,您不能将 ids 放在复选框值中,因为复选框的值可以是真或假。

Try to use html.HiddenFieldFor(model => model.YourModel[i]) and replace foreach by for.尝试使用 html.HiddenFieldFor(model => model.YourModel[i]) 并将 foreach 替换为 for。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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