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
- What is Client Side?
- What is Server Side?
- @Html.Dropdownlist vs @Html.DropdownlistFor
- Step by Step implementation to receive dropdownlist selected value.
- 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
- USE [MBKTest]
- GO
-
- /****** Object: Table [dbo].[tblCities] Script Date: 30-Nov-17,Thu 6:34:14 PM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE TABLE [dbo].[tblCities](
- [CityID] [int] IDENTITY(1,1) NOT NULL,
- [CityName] [nvarchar](50) NULL
- ) ON [PRIMARY]
-
- GO
tblCities records
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
- <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.
- HTTPGET - This method will execute while user calls memberentry from browser.
- HTTPPOST - This method will execute while we submit the memberentry form to server.
Attach namespace at the top of the controller.
- System.Configuration
- System.Data
- 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.
Write following code in MemberModel.cs file
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace DropdownListValueMVC.Models
- {
- public class MemberModel
- {
- public int MmeberID { get; set; }
- public string MemberName { get; set; }
- public string City { get; set; }
- public string PhoneNumber { get; set; }
- }
- }
Before moving ahead please build the solution.
Now write DropdownListValueMVC.Models namespace at the top in Home controller file.
- using DropdownListValueMVC.Models; (To receive the Models in Home controller)
Now write following code in Home Controller’s HttpGet action method of MemberEntry.
- [HttpGet]
- public ActionResult MemberEntry()
- {
- string constr = ConfigurationManager.ConnectionStrings["mbkConnectionString"].ToString();
- SqlConnection _con = new SqlConnection(constr);
- SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCities", constr);
- DataTable _dt = new DataTable();
- _da.Fill(_dt);
- ViewBag.CityList = ToSelectList(_dt,"CityID","CityName");
-
- return View();
- }
Now its time to create a VIEW for MemberEntry.
Right Click on HTTPGET’s MemberEntry ActionMethod and select Add View.
As you clicked on Add View… option
Add view dialog box will appear on the screen fill the dialog box as per given details.
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace DropdownListValueMVC
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "MemberEntry", id = UrlParameter.Optional }
- );
- }
- }
- }
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,
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.
- <div class="col-md-10">
- @*ViewBag.CityList is holding all the cities values*@
- @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList, new { @class = "form-control"} )
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
Now run the application following output should come on the screen.
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.
In debug mode you can see the filled model.
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
Code in HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using DropdownListValueMVC.Models;
-
- namespace DropdownListValueMVC.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult About()
- {
- ViewBag.Message = "Your application description page.";
-
- return View();
- }
-
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
-
- return View();
- }
-
- [HttpGet]
- public ActionResult MemberEntry()
- {
- string constr = ConfigurationManager.ConnectionStrings["mbkConnectionString"].ToString();
- SqlConnection _con = new SqlConnection(constr);
- SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCities", constr);
- DataTable _dt = new DataTable();
- _da.Fill(_dt);
- ViewBag.CityList = ToSelectList(_dt,"CityID","CityName");
-
- return View();
- }
-
- [HttpPost]
- public ActionResult MemberEntry(MemberModel _member)
- {
- return View();
- }
-
- [NonAction]
- public SelectList ToSelectList(DataTable table, string valueField, string textField)
- {
- List<SelectListItem> list = new List<SelectListItem>();
-
- foreach (DataRow row in table.Rows)
- {
- list.Add(new SelectListItem()
- {
- Text = row[textField].ToString(),
- Value = row[valueField].ToString()
- });
- }
-
- return new SelectList(list, "Value", "Text");
- }
- }
- }
Code in MemberEntry.cshtml
- @model DropdownListValueMVC.Models.MemberModel
-
- @{
- ViewBag.Title = "MemberEntry";
- }
- <h2>MemberEntry</h2>
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.MmeberID, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MmeberID, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.MmeberID, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.MemberName, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @*ViewBag.CityList is holding all the cities values*@
- @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList, new { @class = "form-control" } )
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
OUTPUT
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.
- @onChange = "SelectedValue(this)"
Code to implement ONCHANGE event of javascript
- @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
- <script>
-
- function SelectedValue(ddlObject)
- {
-
- var selectedValue = ddlObject.value;
-
- var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
-
-
- alert(" Selected Value: " + selectedValue+" -- "+"Selected Text: " + selectedText ) ;
- }
- </script>
In client side implementation we had changed only MemberEntry.cshtml VIEW file.
Code in MemberEntry.Cshtml
- @model DropdownListValueMVC.Models.MemberModel
-
- @{
- ViewBag.Title = "MemberEntry";
- }
- <h2>MemberEntry</h2>
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.MmeberID, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MmeberID, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.MmeberID, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.MemberName, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @*ViewBag.CityList is holding all the cities values*@
- @Html.DropDownListFor(model => model.City,ViewBag.CityList as SelectList, new { @class = "form-control", @onChange = "SelectedValue(this)" } )
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
-
- }
-
- <script>
-
- function SelectedValue(ddlObject)
- {
-
- var selectedValue = ddlObject.value;
-
- var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
-
-
- alert(" Selected Value: " + selectedValue+" -- "+"Selected Text: " + selectedText ) ;
- }
- </script>
OUTPUT
Happy Coding…