dropdownlist in mvc from database

How to bind dropdownlist in mvc from database?

Ex:

Controller:

    private static List<SelectListItem> PopulateFruits()

    {

        List<SelectListItem> items = new List<SelectListItem>();

        string constr = ConfigurationManager.ConnectionStrings[“Constring”].ConnectionString;

        using (SqlConnection con = new SqlConnection(constr))

        {

            string query = ” SELECT FruitName, FruitId FROM Fruits”;

            using (SqlCommand cmd = new SqlCommand(query))

            {

                cmd.Connection = con;

                con.Open();

                using (SqlDataReader sdr = cmd.ExecuteReader())

                {

                    while (sdr.Read())

                    {

                        items.Add(new SelectListItem

                        {

                            Text = sdr[“FruitName”].ToString(),

                            Value = sdr[“FruitId”].ToString()

                        });

                    }

                }

                con.Close();

            }

        }

        return items;

    }

}

View Page:

        <tr>

                <td>

                    Fruit:

                </td>

                <td>

                    @Html.DropDownListFor(m => m.FruitId, Model.Fruits, “Please select”)

                </td>

            </tr>

Leave a comment

Your email address will not be published. Required fields are marked *