复选框未在 webgrid 中被选中

Checkbox is not getting checked inside webgrid

当我 运行 此代码时,所有复选框都显示为未选中。

@{
    var grid = new WebGrid(Model);
}

<div id="gridContent" style=" padding:20px; ">
    @grid.GetHtml(
        tableStyle: "webgrid-table",
        headerStyle: "webgrid-header",
        footerStyle: "webgrid-footer",
        alternatingRowStyle: "webgrid-alternating-row",
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
        mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
            grid.Column(columnName: "ID", header: "ID", format: @<text>@item.ID</text>),
            grid.Column(columnName: "FirstName", header: "First Name", format: @<text>@item.FirstName</text> ),
            grid.Column(columnName: "LastName", header: "Last Name", format: @<text>@item.LastName</text>),
            grid.Column(header: "IsActive",
            format: @<text><input id="select" class="box" name="select" type="checkbox" value="@item.IsActive" /></text>,
            style: "text-center checkbox-width")
            ))
</div>

IsActive 始终具有 true 作为值。模型 class 看起来像:

public class Student
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsActive { get; set; }

    public IList<Student> GetStudents()
    {
        string connectionStringName = System.Configuration.ConfigurationManager.ConnectionStrings["StudentDBContext"].ConnectionString;
        IList<Student> _Student = new List<Student>();

        using (SqlConnection connection = new SqlConnection(connectionStringName))
        {
            SqlCommand command = new SqlCommand(
              "SELECT ID, FirstName,LastName,IsActive FROM Student;", connection);

            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    _Student.Add(new Student()
                    {
                        ID = Convert.ToInt32(reader["ID"].ToString()),
                        FirstName = reader["FirstName"].ToString(),
                        LastName = reader["LastName"].ToString(),
                        IsActive = Convert.ToBoolean(reader["IsActive"])
                    });
                }
            }
            reader.Close();
        }

        return _Student;
    }

    public Student()
    {
    }
}

只是不明白我哪里弄错了

而不是:

<input id="select" class="box" name="select" type="checkbox" value="@item.IsActive" />

你应该这样做:

<input id="select" class="box" name="select" type="checkbox" @(item.IsActive ? "checked='checked'" : "") value="@item.IsActive" />

有关如何选中复选框的详细信息here