Search Your Dot Net Topic

Monday 8 January 2018

Dropdownlist in ASP.NET MVC

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 attached javascript standard event like onChange to Control.



Before proceeding towards step by step first we go through 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 weak typed.
1. This is strongly typed.
2. Do not support lambda expression
2. Support lambda expression.
3. Need to supply property name as string
3. Directly coupled with model.


STEP BY STEP IMPLEMENTATION

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 :

Dropdown List  Asp.Net MVC Tutor in Malad East
Dropdown List  Asp.Net MVC, Tutor in Malad East





















DropdownList in Asp.Net MVC Tutor in Malad West ,  Asp.Net MVC Tutor in Kandivali West,
DropdownList in Asp.Net MVC Tutor in Malad West

DropdownList in Asp.net MVC tutor in Surat, Asp.net MVC tutor in Ahemdabad
DropdownList in Asp.net MVC tutor in Surat
DropdownList in Asp.Net MVC tutor in Kandivali East ,  Asp.Net MVC tutor in Mira Road
DropdownList in Asp.Net MVC tutor in Kandivali East ,  Asp.Net MVC tutor in Mira Road
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.
1. HTTPGET
2. HTTPPOST

1. HTTPGET: This method will execute while user call 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.

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.

DropdownList in Asp.Net MVC Bhayandar East , Asp.Net MVC Bhayandar West
DropdownList in Asp.Net MVC Bhayandar East

DropdownList Asp.Net Tutor in Kalwa, Asp.Net Tutor in Thane
DropdownList Asp.Net Tutor in Kalwa, Asp.Net Tutor in Thane

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.
Dropdownlist-Asp.Net-MVC-Tutor-Vasai East , Asp.Net-MVC-Tutor-Vasai West
Dropdownlist-Asp.Net-MVC-Tutor-Vasai East , Asp.Net-MVC-Tutor-Vasai West


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 MVC Malad-East,  DropdownList in Asp.net MVC Malad-West
DropdownList in Asp.net MVC Malad-East,  DropdownList in Asp.net MVC Malad-West

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:




DEFAULT OUTPUT of MemberEntry View:

Dropdownlist-Asp.Net-MVC-Tutor-Nalasopara - East , Asp.Net-MVC-Tutor-Nalasopara - West
Dropdownlist-Asp.Net-MVC-Tutor-Nalasopara - East , Asp.Net-MVC-Tutor-Nalasopara - West 
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.
Dropdownlist-Asp.Net-MVC-Tutor-Malad-East , Dropdownlist-Asp.Net-MVC-Tutor-Goregoan-West
Dropdownlist-Asp.Net-MVC-Tutor-Malad-East , Dropdownlist-Asp.Net-MVC-Tutor-Goregoan-West



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-Asp.Net-MVC-Tutor-Goregoan-West-Mumbai, Asp.Net-MVC-Tutor-Andheri-West
Dropdownlist-Asp.Net-MVC-Tutor-Goregoan-West-Mumbai, Asp.Net-MVC-Tutor-Andheri-West

In debug mode you can see the filled model.

Dropdownlist-Asp.Net MVC Tutor Goregoan West , Dropdownlist-Asp.Net MVC Tutor Goregoan
Dropdownlist-Asp.Net MVC Tutor Goregoan West , Dropdownlist-Asp.Net MVC Tutor Goregoan

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-Asp.Net-MVC-Tutor-Mumbai-Virar
Dropdownlist-Asp.Net-MVC-Tutor-Malad-Virar-Mumbai



























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:

DropdownList Asp.Net MVC Tutor  Malad West , Asp.Net MVC Tutor  Kandivali-East
DropdownList Asp.Net MVC Tutor  Malad West , Asp.Net MVC Tutor  Kandivali-East


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>
    //To get selected value an text of dropdownlist
    function SelectedValue(ddlObject)
    {
        //Selected value of dropdownlist
        var selectedValue = ddlObject.value;
        //Selected text of dropdownlist
        var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
        
        //alert popup with detail of seleceted value and text
        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>
    //To get selected value an text of dropdownlist
    function SelectedValue(ddlObject)
    {
        //Selected value of dropdownlist
        var selectedValue = ddlObject.value;
        //Selected text of dropdownlist
        var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
        
        //alert popup with detail of seleceted value and text
        alert(" Selected Value: " + selectedValue+" -- "+"Selected Text: " + selectedText ) ;
    }
</script>

OUTPUT:
Dropdownlist-Asp.Net-MVC-Tutor-Andheri-West , Asp.Net-MVC-Tutor-Andheri-East
Dropdownlist-Asp.Net-MVC-Tutor-Andheri-West , Asp.Net-MVC-Tutor-Andheri-East


Happy Coding…





No comments:

Post a Comment