DropDownList In ASP.NET MVC

Main Object of Article

  • Bind Dropdownlist control with Data
  • Get Server side selected value of Dropdownlist
  • Get Client side selected value of Dropdonwlist 

In this article you will come know how to bind data and get dropdownlist selected value in Asp.Net MVC in Client Side and Server Side.

Article throw lights on following topics

  1. What is Client Side?
  2. What is Server Side?
  3. @Html.Dropdownlist vs @Html.DropdownlistFor
  4. Step by Step implementation to receive dropdownlist selected value.
  5. While you go through step by step you come to know following things:
    • What is HTTPGET?
    • What is HTTPPOST?
    • Used Namespace detail.
    • How to attach javascript standard event like onChange to Control. 

Before proceeding step by step first we will go through the meaning of Client Side and Server Side. 

Client Side

Getting the selected dropdownlist value without form submission to server. Receive the value with the help Javascript or Jquery.

Server Side

Getting the selected dropdownlist value in server side while user submit the form. Thats called HTTP-POST.

@Html.Dropdownlist vs @Html.DropdownlistFor

@Html.Dropdownlist @Html.DropdownlistFor
1. This is weakly typed. 1. This is strongly typed.
2. Does not support lambda expression 2. Support lambda expression.
3. Need to supply property name as string 3. Directly coupled with model.

STEP BY STEP SERVER SIDE BINDING DATA AND GETTING SELECTED VALUE OF DROPDOWNLIST CONTROL

Create tblCities table for Dropdownlist datas,

SQL Script 

  1. USE [MBKTest]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[tblCities]    Script Date: 30-Nov-17,Thu 6:34:14 PM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[tblCities](  
  12.     [CityID] [int] IDENTITY(1,1) NOT NULL,  
  13.     [CityName] [nvarchar](50) NULL  
  14. ON [PRIMARY]  
  15.   
  16. GO  

tblCities records 

Dropdownlist in ASP.NET

Dropdownlist in ASP.NET

Dropdownlist in ASP.NET

Dropdownlist in ASP.NET

Switch to solution explorer by pressing keys CTRL + ALT + L and double click on Web.Config and insert connection string inside configuration-->ConnectionStrings tag

Connection Strings

  1. <add name="mbkConnectionString" connectionString="Data Source=admin;Initial Catalog=MBkTest;Persist Security Info=True;User ID=sa;Password=clserver2" providerName="System.Data.SqlClient"/>  

Double click on Home controller which located inside Controllers folder.

Inside Home Controller going to create two method of MemberEntry.

  1. HTTPGET - This method will execute while user calls memberentry from browser.
  2. HTTPPOST - This method will execute while we submit the memberentry form to server.

Attach namespace at the top of the controller.

  1. System.Configuration  
  2. System.Data  
  3. System.Data.SqlClient  

Uses of following Namespace:

Namespace Uses
System.Configuration To get connection strings from web.config file.
System.Data To get dataset, object.
System.Data.SqlClient To get SqlConnection, SqlDataAdapter

Now add model called “MemberModel” into Models folder.

Dropdownlist in ASP.NET

Dropdownlist in ASP.NET

Write following code in MemberModel.cs file

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace DropdownListValueMVC.Models  
  7. {  
  8.     public class MemberModel  
  9.     {  
  10.         public int MmeberID { get; set; }  
  11.         public string MemberName { get; set; }  
  12.         public string City { get; set; }  
  13.         public string PhoneNumber { get; set; }  
  14.     }  
  15. }  

Before moving ahead please build the solution.

Now write DropdownListValueMVC.Models namespace at the top in Home controller file.

  1. using DropdownListValueMVC.Models; (To receive the Models in Home controller)  

Now write following code in Home Controller’s HttpGet action method of MemberEntry.

  1. [HttpGet]  
  2.         public ActionResult MemberEntry()  
  3.         {  
  4.             string constr = ConfigurationManager.ConnectionStrings["mbkConnectionString"].ToString();  
  5.             SqlConnection _con = new SqlConnection(constr);  
  6.             SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCities", constr);  
  7.             DataTable _dt = new DataTable();  
  8.             _da.Fill(_dt);  
  9.             ViewBag.CityList = ToSelectList(_dt,"CityID","CityName");  
  10.   
  11.             return View();  
  12.         }  

Now its time to create a VIEW for MemberEntry.

Right Click on HTTPGET’s MemberEntry ActionMethod and select Add View.

Dropdownlist in ASP.NET

As you clicked on Add View… option

Add view dialog box will appear on the screen fill the dialog box as per given details.

Dropdownlist in ASP.NET

Before running the our application to view the MemberEntry action-method view, first we should change the default running action method as MemberEntry of Home Controller.

Switch to Solution explorer and click on App_Start folder then double click on RouteConfig.cs.

In routeconfig.cs file we can change the default running controller and action-method names.

Code In RouteConfig.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace DropdownListValueMVC  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Home", action = "MemberEntry", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  

NOTE

Without changing of default routeconfig.cs its can run but every time we have to write complete url like this,

http://localhost:56681/home/memberentry

DEFAULT OUTPUT of MemberEntry View,

Dropdownlist in ASP.NET
Switch to Solution Explorer and double click on Views folder --> Home Folder then click on MemberEntry.cshtml. 

Remove current code of model.City and replace or upate the following code.

  1. <div class="col-md-10">  
  2.    @*ViewBag.CityList is holding all the cities values*@  
  3.    @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList,  new { @class = "form-control"} )  
  4.    @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  5. </div>  

Now run the application following output should come on the screen.

Dropdownlist in ASP.NET

Now you can check city records already bind with Dropdownlist control.

Fill the member data entry form and click on Create button.

Here CREATE button will functioning as submit button and pointer or control transfer to HTTPOST post method of MemberEntry.

Dropdownlist in ASP.NET

In debug mode you can see the filled model. 

Dropdownlist in ASP.NET

For your reference here given city id and city name list. As above image showing City = 11 in following city list image you can cross check CityID = 11 equal to Shirdi

Dropdownlist in ASP.NET

Code in HomeController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Configuration;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using DropdownListValueMVC.Models;  
  10.   
  11. namespace DropdownListValueMVC.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         public ActionResult Index()  
  16.         {  
  17.             return View();  
  18.         }  
  19.   
  20.         public ActionResult About()  
  21.         {  
  22.             ViewBag.Message = "Your application description page.";  
  23.   
  24.             return View();  
  25.         }  
  26.   
  27.         public ActionResult Contact()  
  28.         {  
  29.             ViewBag.Message = "Your contact page.";  
  30.   
  31.             return View();  
  32.         }  
  33.   
  34.         [HttpGet]  
  35.         public ActionResult MemberEntry()  
  36.         {  
  37.             string constr = ConfigurationManager.ConnectionStrings["mbkConnectionString"].ToString();  
  38.             SqlConnection _con = new SqlConnection(constr);  
  39.             SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCities", constr);  
  40.             DataTable _dt = new DataTable();  
  41.             _da.Fill(_dt);  
  42.             ViewBag.CityList = ToSelectList(_dt,"CityID","CityName");  
  43.   
  44.             return View();  
  45.         }  
  46.   
  47.         [HttpPost]  
  48.         public ActionResult MemberEntry(MemberModel _member)  
  49.         {  
  50.             return View();  
  51.         }  
  52.   
  53.         [NonAction]  
  54.         public SelectList ToSelectList(DataTable table, string valueField, string textField)  
  55.         {  
  56.             List<SelectListItem> list = new List<SelectListItem>();  
  57.   
  58.             foreach (DataRow row in table.Rows)  
  59.             {  
  60.                 list.Add(new SelectListItem()  
  61.                 {  
  62.                     Text = row[textField].ToString(),  
  63.                     Value = row[valueField].ToString()  
  64.                 });  
  65.             }  
  66.   
  67.             return new SelectList(list, "Value""Text");  
  68.         }  
  69.     }  
  70. }  

Code in MemberEntry.cshtml

  1. @model DropdownListValueMVC.Models.MemberModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "MemberEntry";  
  5. }  
  6. <h2>MemberEntry</h2>  
  7.   
  8. @using (Html.BeginForm())   
  9. {  
  10.     @Html.AntiForgeryToken()  
  11.       
  12.     <div class="form-horizontal">  
  13.         <h4>MemberModel</h4>  
  14.         <hr />  
  15.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.MmeberID, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.MmeberID, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.MmeberID, ""new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.   
  24.         <div class="form-group">  
  25.             @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })  
  26.             <div class="col-md-10">  
  27.                 @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })  
  28.                 @Html.ValidationMessageFor(model => model.MemberName, ""new { @class = "text-danger" })  
  29.             </div>  
  30.         </div>  
  31.   
  32.         <div class="form-group">  
  33.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  34.             <div class="col-md-10">  
  35.                 @*ViewBag.CityList is holding all the cities values*@  
  36.                 @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList,  new { @class = "form-control" } )  
  37.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  38.             </div>  
  39.         </div>  
  40.   
  41.         <div class="form-group">  
  42.             @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })  
  43.             <div class="col-md-10">  
  44.                 @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })  
  45.                 @Html.ValidationMessageFor(model => model.PhoneNumber, ""new { @class = "text-danger" })  
  46.             </div>  
  47.         </div>  
  48.   
  49.         <div class="form-group">  
  50.             <div class="col-md-offset-2 col-md-10">  
  51.                 <input type="submit" value="Create" class="btn btn-default" />  
  52.             </div>  
  53.         </div>  
  54.     </div>  
  55. }  
  56.   
  57. <div>  
  58.     @Html.ActionLink("Back to List""Index")  
  59. </div>  
  60.   
  61. @section Scripts {  
  62.     @Scripts.Render("~/bundles/jqueryval")  
  63. }  

OUTPUT

Dropdownlist in ASP.NET

STEP BY STEP CLIENT SIDE GETTING SELECTED VALUE OF DROPDOWNLIST

To receive the selected value of dropdown list in client side we have to call ONCHANGE event of javascript. In this we will achieve the task only by changing VIEW FILE (MemberEntry.CSHTML)

ONCHANGE event we will call a function.

  1. @onChange = "SelectedValue(this)"  

Code to implement ONCHANGE event of javascript

  1. @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList,  new { @class = "form-control",  @onChange = "SelectedValue(this)" } )  

Javascript code write at the bottom of MemberEntry.Cshtml

  1. <script>  
  2.     //To get selected value an text of dropdownlist  
  3.     function SelectedValue(ddlObject)  
  4.     {  
  5.         //Selected value of dropdownlist  
  6.         var selectedValue = ddlObject.value;  
  7.         //Selected text of dropdownlist  
  8.         var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;  
  9.           
  10.         //alert popup with detail of seleceted value and text  
  11.         alert(" Selected Value: " + selectedValue+" -- "+"Selected Text: " + selectedText ) ;  
  12.     }  
  13. </script>  

In client side implementation we had changed only MemberEntry.cshtml VIEW file.

Code in MemberEntry.Cshtml

  1. @model DropdownListValueMVC.Models.MemberModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "MemberEntry";  
  5. }  
  6. <h2>MemberEntry</h2>  
  7.   
  8. @using (Html.BeginForm())   
  9. {  
  10.     @Html.AntiForgeryToken()  
  11.       
  12.     <div class="form-horizontal">  
  13.         <h4>MemberModel</h4>  
  14.         <hr />  
  15.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.MmeberID, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.MmeberID, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.MmeberID, ""new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.   
  24.         <div class="form-group">  
  25.             @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })  
  26.             <div class="col-md-10">  
  27.                 @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })  
  28.                 @Html.ValidationMessageFor(model => model.MemberName, ""new { @class = "text-danger" })  
  29.             </div>  
  30.         </div>  
  31.   
  32.         <div class="form-group">  
  33.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  34.             <div class="col-md-10">  
  35.                 @*ViewBag.CityList is holding all the cities values*@  
  36.                 @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList,  new { @class = "form-control",  @onChange = "SelectedValue(this)" } )  
  37.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  38.             </div>  
  39.         </div>  
  40.   
  41.         <div class="form-group">  
  42.             @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })  
  43.             <div class="col-md-10">  
  44.                 @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })  
  45.                 @Html.ValidationMessageFor(model => model.PhoneNumber, ""new { @class = "text-danger" })  
  46.             </div>  
  47.         </div>  
  48.   
  49.         <div class="form-group">  
  50.             <div class="col-md-offset-2 col-md-10">  
  51.                 <input type="submit" value="Create" class="btn btn-default" />  
  52.             </div>  
  53.         </div>  
  54.     </div>  
  55. }  
  56.   
  57.   
  58. <div>  
  59.     @Html.ActionLink("Back to List""Index")  
  60. </div>  
  61.   
  62. @section Scripts {  
  63.     @Scripts.Render("~/bundles/jqueryval")  
  64.   
  65. }  
  66.   
  67. <script>  
  68.     //To get selected value an text of dropdownlist  
  69.     function SelectedValue(ddlObject)  
  70.     {  
  71.         //Selected value of dropdownlist  
  72.         var selectedValue = ddlObject.value;  
  73.         //Selected text of dropdownlist  
  74.         var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;  
  75.           
  76.         //alert popup with detail of seleceted value and text  
  77.         alert(" Selected Value: " + selectedValue+" -- "+"Selected Text: " + selectedText ) ;  
  78.     }  
  79. </script>  

OUTPUT

Dropdownlist in ASP.NET

Happy Coding…


Similar Articles