Jaya Prakash

Jaya Prakash

  • 540
  • 2.3k
  • 67.1k

Binding DropDown to db using html helpers

Dec 8 2022 3:32 PM

specified cast is not valid while i am trying to bind dropdownlist value to db **I want to Take the value from dropdown from model and when i click on create it should insert into db table instead of inserting deptartment names interger values are assigning to the column Pls help me ** My Model

public Departments DeptNames { get; set; } 
public enum Departments
{
    ECE=1,
    CSE=2,
    MECH=3,
    CIVIL=4
}

MY Repository

public List<ModelClass> ShowListOfUserDetails()
{
        List<ModelClass> models = new List<ModelClass>();
        SqlCommand cmd = new SqlCommand("sp_ShowUserDetails", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        con.Open();
        da.Fill(dt);
        con.Close();
        foreach (DataRow dr in dt.Rows)
        {
            models.Add(new ModelClass
            {
                Id = Convert.ToInt32(dr["pid"]),
                Name = Convert.ToString(dr["namee"]),
                City = Convert.ToString(dr["city"]),
                Address = Convert.ToString(dr["addresss"]),
                Gender = Convert.ToString(dr["gender"]),
                DeptNames = (ModelClass.Departments)dr["department"]
            });
        }
    return models;
}

MY View

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem =>item.Id)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.City)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Address)
    </td>
    <td>
        @Html.DisplayFor(modelItem=>item.Gender)
    </td>
    <td>
        @Html.DisplayFor(modelItem=>item.DeptNames)
    </td>
    <td>
</tr>

Answers (1)