Saturday, 25 August 2012

How to bind data from database to Dropdown in Mvc :

Hie... in mvc after we calling the View that by default it 'll first goes to the index... in that before rendering that view i'm calling function which captures the data from DB i'm using selected list item...
   For selectedlistitem it having three values text,value,selected these it holds the data value as well text that ve to show in dropdown... i'm returning that to the controller and there i'm taking "VIEWBAG" it makes easy to show the viewbag.object values in Razor syntax here is the code.. follow for my procedure...

In my controller:
           public ActionResult Index()

        {
           List<SelectListItem> states= Contact.fillcombobox();
           ViewBag.stateddp = states;
             return View();
        }

And My Method is:

        public static List<SelectListItem> fillcombobox()
        {
 string connString =  ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand();
            SqlDataReader dr;
            cmd.CommandText = "select * from tablestates";
            cmd.Connection = conn;
            conn.Open();
            dr=cmd.ExecuteReader();
        
            List<SelectListItem> statenames = new List<SelectListItem>();
            if (dr.HasRows)
            {

                while (dr.Read())
                {
statenames.Add(new SelectListItem() { Text = dr["state"].ToString(),Value =dr["id"].ToString() 

           });
                }
            }
                    
            conn.Close();
            return statenames;
        }


And in my View for Razor syntax my Dropdown 'll be:

               @Html.DropDownList("Stateddp")

    then it'll show the data that comming from DB will be shown in my dropdown.... 

No comments:

Post a Comment