How to bind Dropdownlist in asp.net mvc3 Dynamically


Static Binding:

Write Following code in action method in controller

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to the Training Courses...";
            List objcourses = new List();
            objcourses.Add("Asp.Net");
            objcourses.Add("MVC");
            objcourses.Add("WCF");
            objcourses.Add("WPF");
            objcourses.Add("C#.Net");
            ViewBag.Courses = new SelectList(objcourses);
            return View();
        }
    }

Then write following code in Related view(Index view)

@{
    ViewBag.Title = "Home Page";
}

Index
@using(@Html.BeginForm(“Index”,”Home”,FormMethod.Get)) {

Courses List; @Html.DropDownList(“Courses“)

}

Dynamic Binding:

first create database and retrive data from table using sqlclient or entity framework now i am showing using entity framework

Write Following code in action method in controller

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            private MovieDBContext db = new MovieDBContext();
            var GenreLst = new List();
            var GenreQry = from d in db.Movies
                           orderby d.Genre
                           select d.Genre;
            GenreLst.AddRange(GenreQry.Distinct());
            ViewBag.Courses = new SelectList(GenreLst);
            return View();
        }
    }
Then write following code in Related view(Index view)

@{
    ViewBag.Title = "Home Page";
}
Index

@using(@Html.BeginForm("Index","Home",FormMethod.Get)) {

Courses List; @Html.DropDownList("Courses")
}
Advertisements

5 thoughts on “How to bind Dropdownlist in asp.net mvc3 Dynamically

  1. This is really nice article . while surfing i have found one more very interesting link as same.www.dotnetpools.com/Article/ArticleDetiail/?articleId=48&title=Binding+Dropdownlist+In+MVC3+Using+C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s