未在webgrid

时间:2015-12-15 14:43:35

标签: c# html asp.net-mvc razor webgrid

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

@{
    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 始终具有真实值。模型类看起来像:

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()
    {
    }
}

只是不明白我犯了哪个错误。

1 个答案:

答案 0 :(得分:1)

而不是:

<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的更多信息。