mercredi 29 janvier 2020

How to add dynamic checkbox from database

I'm trying this first time and I'm confused. I have two tables TblEmployee and tblHobby. In tblEmployee I have a Hobby column. I'm trying to add checkbox for this Hobby column from tblHobby.

In tblHobby I have two columns Id and HobbyName. I'm confused as to how to get data fron other table in database - please suggest a solution

This method is the one to fetch the hobby entries:

private void PopulateHobbies(Hobby hby)
{
    using (SqlConnection con = new SqlConnection(ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select * from tblHobby";
            cmd.Connection = con;

            con.Open();

            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                 while (rdr.Read())
                 {
                     ListItem item = new ListItem();
                     item.Text = rdr["HobbyName"].ToString();
                     item.Value = rdr["Id"].ToString();
                     item.Selected = Convert.ToBoolean(rdr["IsSelected"]);
                 }
             }

             con.Close();
         }
     }
}

This us my AddEmployee method:

public void AddEmployee(Employee emp)
{
    using (SqlConnection con = new SqlConnection(ConnectionString))
    {
        SqlCommand cmd = new SqlCommand("spaddEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@FirstName", emp.FirstName);
        cmd.Parameters.AddWithValue("@LastName", emp.LastName);
        cmd.Parameters.AddWithValue("@Gender", emp.Gender);
        cmd.Parameters.AddWithValue("@DOB", Convert.ToDateTime(emp.DOB));
        cmd.Parameters.AddWithValue("@Hobby",emp.Hobby);
        cmd.Parameters.AddWithValue("@Photo", emp.Photo);
        cmd.Parameters.AddWithValue("@City", emp.City);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

And this is my Create page

<div class="form-group">
    @Html.LabelFor(model => model.Hobby, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @*@Html.CheckBoxFor(Model => Model.Hobby, htmlAttributes: new { @class = "control-label col-md-2" })*@
    </div>
    @Html.ValidationMessageFor(model => model.Hobby, "", new { @class = "text-danger" })
</div>



Aucun commentaire:

Enregistrer un commentaire