Click here to Skip to main content
15,884,628 members
Articles / Web Development / HTML
Tip/Trick

Dynamic DropDownList Binding in ASP.NET MVC With Database

Rate me:
Please Sign up or sign in to vote.
4.85/5 (15 votes)
14 Aug 2014CPOL3 min read 156K   2.3K   28   16
Cascading DropDownList in ASP.NET MVC

Introduction

This is my second Tip/trick and this Tip/trick is all about how we can create a dynamic dropdown list in ASP .NET MVC. In MVC mostly user find difficulties to bind the the data to user the controles. so here i am going to show a simple application demo in which we will bind the data to dropdown list from the databse at the runtime.

Background

This demo application contains the javascript and simple logic of ADO.NET. little concept of ASP.NET MVC and javascript is enough to understand this demo.

Design

Motive - Now my goal is to create a application team_statistics which will contain the 3 dropdownlist.

first dropdownlist - It will contain the type of tournaments and these data will come from the database.

second dropdownlist - On selection of the tournament type from the first dropdownlist second dropdownlist automatically should generate the teams from the database.

third dropdownlist - On selection of the type of team from the second dropdown list the third dropdownlist should generate the player name.

So to create this application we need three table.

Following are the steps to create the application:

  1. Open Visual Studio and select the new Project.
  2. Within the Web template, select ASP.NET MVC4 WEB Application with empty template.
  3. Now add a Home Controller and a view Page for Index Action Method.
  4. Now add a database file .mdf file in your project. This can be added by right clicking on App_data folder and add a database file.
  5. In the database file, add 3 tables by the name of Player, Team, TounamentType.
  6. below diagram give the complete idea about the database.

Image 1.

Using the code

Here is the complete code for fetching the data from the database and passing the data to the UI.

C++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Data.Sql;


namespace team_statistics.Controllers
{

   public class HomeController : Controller    
    {
       string connection = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
       List<selectlistitem> team = new List<selectlistitem>();             
       List<selectlistitem> player = new List<selectlistitem>();      //declare the 3 list object
       List<selectlistitem> tournament = new List<selectlistitem>();
       public ActionResult Index()
       {
          ViewBag.var1 = GetOptions();   //first request come and move to this method
          ViewBag.var2 = team;  
           ViewBag.var3 = player;
           return View();
       }     
                      //var1,var2,var3 are the objects to pass the data from controller to index
          
       
 private SelectList GetOptions()           //fetch the tournament type details from the table
  {
    using (SqlConnection conn = new SqlConnection(connection))
      {
         conn.Open();
          SqlDataReader myReader = null;
          SqlCommand myCommand = new SqlCommand("SELECT Id, Tournament FROM TounamentType", conn);
           myReader = myCommand.ExecuteReader();
            while (myReader.Read())
             {

            tournament.Add(new SelectListItem { Text = myReader["Tournament"].ToString(), Value =             myReader["Id"].ToString() });
             }
      
              conn.Close();
              return new SelectList(tournament, "Value", "Text", "id");  //return the list objects
               
            }
        }

   
     
        
 public JsonResult Team(string name)  //fetch the team details from database
     {
       using (SqlConnection conn = new SqlConnection(connection))
         {
            conn.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select Team,Id from Team where Tournament =                 '" + name + "' ", conn);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
             {
               team.Add(new SelectListItem { Text = myReader["Team"].ToString(), Value =                         myReader["Id"].ToString() });
             }
            }
           return Json(team, JsonRequestBehavior.AllowGet); //return the list objects in json form
        }


   public JsonResult Player(string name) // fetch the details of player from database
        {
           using (SqlConnection conn = new SqlConnection(connection))
            {   
                conn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("select Player,Id from Player where Team =                  '" + name + "' ", conn);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                 player.Add(new SelectListItem { Text = myReader["Player"].ToString(), Value =                     myReader["Id"].ToString() });
                }
            }
            
         return Json(player, JsonRequestBehavior.AllowGet); //return the list objects in json form

        }
        }

       
    }

Now I am going to show the UI for this application.

C++
 <h2>Index</h2>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script src="../../Scripts/modernizr-2.5.3.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>

Tournament    @Html.DropDownList("var1","Choose tournament")
Team          @Html.DropDownList("var2","Choose team")  
Player        @Html.DropDownList("var3", "Choose player")
                                   //dropdown with name var1, var2,var3 and with viewbag object
<script type="text/javascript">    //initial var2, var3 are empty 
                                  //dropdownlist name and viewbag object name must be same

$(function () {     
      $("#var1").change(function () {             
           var name = $("#var1 :selected").text();  //if user select the tournament 
           var url = 'Home/Team'; 
            var data1 = { "name": name };
       $.post(url, data1, function (data) {    //ajax call
           var items = [];
           items.push("<option value=" + 0 + ">" + "Choose team" + "</option>"); //first item
           for (var i = 0; i < data.length; i++) {
           items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>"); 
          }                                         //all data from the team table push into array
            $("#var2").html(items.join(' '));  
      })                                            //array object bind to dropdown list
   }); 

    $("#var2").change(function () {                  //same logic for 3rd dropdown list
          var name = $("#var2 :selected").text();

          var url = 'Home/Player';  
           var data1 = { "name": name };
      $.post(url, data1, function (data) { 
             var items = [];
             items.push("<option value=" + 0 + ">" + "Choose Player" + "</option>"); 
             for (var i = 0; i < data.length; i++) {
        items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>");
            }
       $("#var3").html(items.join(' '));  
       }) 
   }); 

});

</script>

<input type="submit" value="submit" />

Result

Here is our final UI page which will show the result.

Image 2

In our final page we can see that there are three dropdownlist. so if user select tournament from the dropdownlist then Team will be appear according to the Tournament and if we select the team from the dropdownlist then player will be appear according to team.

For complete idea you can download and debug the application.

Points that are Important to Run this Application

In Web.Config file change the connection string.

<connectionStrings>
<add name="DBCS" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=E:\team_statistics\team_statistics\App_Data\Team.mdf;
Integrated Security=True; User Instance=True"/>
  </connectionStrings>  // change the connection string

Step 1: To change the connection string, right click on mdf file -> properties->copy the address and replace the attachDbfilename.

Now in this application, you can modify and you can add some extra features like for saving the user data, adding the new data in dropdownlist etc.

I hope you have enjoyed it and got some idea about dynamic dropdownlist binding using JavaScript from this post. Next time i will post some new tip/trick until that enjoy...:)

If some error or wrong concept is there, please comment below as it will be helpful for me.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
India India
I have been working in software area from last 1 year. I have worked on .net technology. I always interested to learn new technology.

Comments and Discussions

 
Questionafter all dis i want to insert dropdown selected text in database....how can i do that? Pin
vishal goyal3-Jun-16 20:35
vishal goyal3-Jun-16 20:35 
BugGot an Invalid object name 'TournamentType' Pin
codejockie7-Apr-16 6:30
professionalcodejockie7-Apr-16 6:30 
GeneralRe: Got an Invalid object name 'TournamentType' Pin
Member 1087225115-Jun-16 18:57
Member 1087225115-Jun-16 18:57 
QuestionGet selected value from dropdownlist Pin
Member 1204943911-Oct-15 3:38
Member 1204943911-Oct-15 3:38 
Questionerror in declare the 3 list object Pin
Member 107242604-May-15 20:15
Member 107242604-May-15 20:15 
QuestionSystem.Dynamic.DynamicObject' does not contain a definition for 'var2' Pin
star_tasneem31-Mar-15 0:02
star_tasneem31-Mar-15 0:02 
AnswerRe: System.Dynamic.DynamicObject' does not contain a definition for 'var2' Pin
Member 108722516-Apr-15 19:54
Member 108722516-Apr-15 19:54 
Bugzip & rar code is corrupted Pin
DSHind28-Mar-15 19:32
DSHind28-Mar-15 19:32 
GeneralRe: zip & rar code is corrupted Pin
Member 108722516-Apr-15 19:24
Member 108722516-Apr-15 19:24 
now check it. now it should work..Smile | :)

GeneralComplement Pin
MayurPadhiyar25-Mar-15 1:04
MayurPadhiyar25-Mar-15 1:04 
GeneralRe: Complement Pin
Member 108722516-Apr-15 19:25
Member 108722516-Apr-15 19:25 
QuestionHow do I get the dynamic dropdown to work in views other than index? Pin
Ragnarök Tarn20-Oct-14 4:59
Ragnarök Tarn20-Oct-14 4:59 
QuestionIssue Pin
surikarthi24-Sep-14 21:40
surikarthi24-Sep-14 21:40 
AnswerRe: Issue Pin
Member 108722513-Oct-14 21:56
Member 108722513-Oct-14 21:56 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun14-Aug-14 20:03
Humayun Kabir Mamun14-Aug-14 20:03 
QuestionDatabase relationships Pin
EarlNet13-Aug-14 3:59
professionalEarlNet13-Aug-14 3:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.