Sunteți pe pagina 1din 1

Home Blog About Us Welcome Guest Register Login

MVC DropDownListFor fill on selection change of another dropdown


SPONSORED SEARCHES

Document Controller

Data Mapping

Post A Blog

Write A Blog

ASP.Net 48

MVC 37

bind child dropdown on change of parent dropdown item? bind dropdown on selection change? bind dropdown by using
jquery? how to return json from action method in controller? how to format child dropdown items cascading GridView 5

dropdownlist in gridview edit mode cascading dropdownlist in mvc cascading dropdownlist jquery mvc cascading
dropdownlist C# 38

Binding DropDownListFor from enum, database and some hard coded values in our previous article MVC 3
DataTable
dropdown binding best ways. In this article we will try to bind child Dropdown on selection change of parent
Dropdown, say Country to State or Sate to City, by using jQuery which will call an action in controller and return Ajax 9
JSON for selected id, and with the help of jQuery append values to child Dropdown. We will try to create page to
add new employee and state and city will be used as parent and child Dropdown. LINQ To SQL 3

SQL Server 32

Angularjs 34

ReactJS 1

Web API 5

JavaScript 13

jQuery 9

HTML 8

CSS 12

XML 6

OOPs 13

Web.Config 2

Let's see the tables we are going to use:


Routing 3

1. public partial class State


2. {
3. public int StateId { get; set; }
4. public string StateName { get; set; }
5. public string Abbr { get; set; }
6. }
7. public partial class City
8. {
9. public int CityId { get; set; }
10. public string CityName { get; set; }
11. public int StateId { get; set; }
12. }
13.

Employee Model:

1. public class Employees


2. {
3. [Key]
4. public int EmployeeId { get; set; }
5.
6. [Required, Display(Name="Employee Name")]
7. public string EmployeeName { get; set; }
8.
9. [Required, Display(Name = "Address")]
10. public String Address { get; set; }
11.
12. [Required, Display(Name = "State")]
13. public int State { get; set; }
14.
15. [Required, Display(Name = "City")]
16. public int City { get; set; }
17.
18. [Display(Name = "Zip Code")]
19. public String ZipCode { get; set; }
20.
21. [Required, Display(Name = "Phone #")]
22. public String Phone { get; set; }
23. }
24.

As you can see, I have not added anything in our model for list of states or cities because we are using Code
first, which will create the database tables, we will try to get data from database and pass to view by using
ViewBag, here is our HttpGet and HttpPost action method:

1. [HttpGet]
2. public ActionResult Create()
3. {
4. ViewBag.StateList = db.States;
5. var model = new Employees();
6. return View(model);
7. }
8. [HttpPost]
9. public ActionResult Create(Employees model)
10. {
11. if (ModelState.IsValid)
12. {
13. // code to save record and redirect to listing page
14. }
15. ViewBag.StateList = db.States;
16. return View(model);
17. }
18.

HTML code for both state and city dropdown:

1. <div class="form-group">
2. @Html.LabelFor(m => m.State, new { @class = "control-label col-md-2" })
3. <div class="col-md-10">
4. @Html.DropDownListFor(m => m.State,
5. new SelectList(ViewBag.StateList, "StateId", "StateName"),
6. "Select state",
7. new { @class = "form-control", @onchange="FillCity()" })
8. @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
9. </div>
10. </div>
11.
12. <div class="form-group">
13. @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
14. <div class="col-md-10">
15. @Html.DropDownListFor(m => m.City,
16. new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
17. "Select city",
18. new { @class = "form-control" })
19. @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
20. </div>
21. </div>
22.

As you can notice we used @onchange="FillCity()" in our State dropdown so we need a JavaScript function
which will be call on change of state. If you are from asp.net background then forgot about the postback, in mvc
there is no postback concept so we don't need viewstate of controls so the pages are light weight. Here is our
FillCity function:

1. @section Scripts {
2. <script>
3. function FillCity() {
4. var stateId = $('#State').val();
5. $.ajax({
6. url: '/Employees/FillCity',
7. type: "GET",
8. dataType: "JSON",
9. data: { State: stateId},
10. success: function (cities) {
11. $("#City").html(""); // clear before appending new list
12. $.each(cities, function (i, city) {
13. $("#City").append(
14. $('<option></option>').val(city.CityId).html(city.CityName));
15. });
16. }
17. });
18. }
19. </script>
20. }
21.

Here we used $.each to loop the items and add item by item to city dropdown. We used to call FillCity action
method in our Employees controller.We need a separate action method which can return cities on the basis of
selection change and return JSON string.

1. public ActionResult FillCity(int state)


2. {
3. var cities = db.Cities.Where(c => c.StateId == state);
4. return Json(cities, JsonRequestBehavior.AllowGet);
5. }
6.

See how we can return json from any action method in our controller. If you want to see the complete html of the
page then it is here.

1. @model MyApp.Models.Employees
2. @{
3. ViewBag.Title = "Index";
4. Layout = "~/Views/Shared/_Layout.cshtml";
5. }
6. <h2>Index</h2>
7. @using (Html.BeginForm())
8. {
9. @Html.AntiForgeryToken()
10.
11. <div class="form-horizontal">
12. <h4>New Employee</h4>
13. <div class="form-group">
14. @Html.LabelFor(m => m.EmployeeName, new { @class = "control-label col-md-2" })
15. <div class="col-md-10">
16. @Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control" })
17. @Html.ValidationMessageFor(m => m.EmployeeName, "", new { @class = "text-danger" })
18. </div>
19. </div>
20. <div class="form-group">
21. @Html.LabelFor(m => m.Address, new { @class = "control-label col-md-2" })
22. <div class="col-md-10">
23. @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
24. @Html.ValidationMessageFor(m => m.Address, "", new { @class = "text-danger" })
25. </div>
26. </div>
27. <div class="form-group">
28. @Html.LabelFor(m => m.State, new { @class = "control-label col-md-2" })
29. <div class="col-md-10">
30. @Html.DropDownListFor(m => m.State,
31. new SelectList(ViewBag.StateList, "StateId", "StateName"),
32. "Select state",
33. new { @class = "form-control", @onchange="FillCity()" })
34. @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
35. </div>
36. </div>
37. <div class="form-group">
38. @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
39. <div class="col-md-10">
40. @Html.DropDownListFor(m => m.City,
41. new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
42. "Select city",
43. new { @class = "form-control" })
44. @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
45. </div>
46. </div>
47. <div class="form-group">
48. @Html.LabelFor(m => m.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
49. <div class="col-md-10">
50. @Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control" })
51. @Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })
52. </div>
53. </div>
54. <div class="form-group">
55. @Html.LabelFor(m => m.Phone, new { @class = "control-label col-md-2" })
56. <div class="col-md-10">
57. @Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })
58. @Html.ValidationMessageFor(m => m.Phone, "", new { @class = "text-danger" })
59. </div>
60. </div>
61. <div class="form-group">
62. <div class="col-md-offset-2 col-md-10">
63. <input type="submit" value="Create" class="btn btn-success" />
64. <a href="/Employees" class="btn btn-warning" >Cancel</a>
65. </div>
66. </div>
67. </div>
68. }
69.

If you want to add more column value into dropdown text you can concatenate them easily, say we want to show
both Id and text in city drop down then we simmply show it like this:

$('<option></option>').
val(city.CityId).html(city.CityId + " - " + city.CityName));

Whatever we see here is not complete to maintain the selected value if we found the model invalid in our post
method and return back to the view then current selected state's cities will be lost same will happen when we
need to fill and select the value in city dropdown for a saved records. We need to add one more JavaScript
method to check on document.ready if there is any value already selected in state dropdown then call the FillCity
method and fill our city dropdown and selected the city value which we get from the model.
I am leaving it for you so you can do a little bit practice, hope you will easily complete it, best of luck.

<< MVC DropDownListFor fill on selection change of another dropdown


MVC EnumDropdownListFor bind with enum example >>
Event Hire Baby Checklist Map of City

Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL
Server). Worked with Metaoption LLC, for more than 9 years and still with the same company.
Always ready to learn new technologies and tricks.
mvc dropdownlistfor jquery javascript

By Ali Adravi On 11 Apr, 15 Viewed: 149,815

Other blogs you may like


mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to
create the same in MVC I faced many problems, how to create model, how to keep searched values in
search controls, pagination, I found myself nowhere, so start searching for some good examples but...
— By Ali Adravi On 25 Aug 2013 Viewed: 36,143

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try
to run an application with “Hello World” and then CRUD functionality. So in this article we will see how
to select records from database (with WebGrid, pagination and sort functionality), update a...
— By Ali Adravi On 17 Aug 2013 Viewed: 99,531

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account
functionality in our application then we need a thanks page after registering with our site, to say thanks
for registering with us or showing confirmation that your password is successfully changed or...
— By Hamden On 30 Jun 2013 Viewed: 3,207

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to
our requirements, so in this article we will use jquery to show the auto complete text box without any
ajax controls. We need a method to get the data from database, a controller method to handle the...
— By Ali Adravi On 29 Jun 2013 Viewed: 6,258

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading
some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC
file upload][1], I promised to post soon about how to upload multiple files. When I was...
— By Ali Adravi On 04 Jun 2013 Viewed: 23,181

32 Comments Advancesharp.com 
1 Login

 Recommend 4 t Tweet f Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Gail Bowen • 3 years ago


Thank you! This was very helpful and saved me a lot of time.
9△ ▽ • Reply • Share ›

Paris Pantigoso • 3 years ago • edited


Hi Ali,

I'm kind of new in MVC but I'm doing my best to learn quickly; however, I'm not able to manage your code in order to make my project work properly...
could you please help me? Here is my Model, Controller, Razor and Script... What am I doing wrong?

Paris
6△ ▽ • Reply • Share ›

ninny kumari • 3 years ago


hey @disqus_amKmj0OZKc did you find some way to do dropdown fills in case of edit. me also facing same problem ?? kindly share if any
3△ ▽ • Reply • Share ›

Ashita Shah > ninny kumari • 2 years ago


Can you pls explain how to do in edit mode.
△ ▽ • Reply • Share ›

최근주 • 2 years ago


hi, how can I declare and use for "db"?

Could you please explain about this?

I need full source code to implement my own.


1△ ▽ • Reply • Share ›

F. Ali Ahmad > 최근주 • 2 years ago


var db = new WhateveryourEntityFrameworkModelName();
1△ ▽ • Reply • Share ›

Ibrar Khan > F. Ali Ahmad • 2 years ago


same problem
△ ▽ • Reply • Share ›

ShaHusn Anr • 2 years ago • edited


Excellent tutorial
1△ ▽ • Reply • Share ›

Gaurav Parmar • 2 years ago


Very Good Article
Thanks
1△ ▽ • Reply • Share ›

disqus_amKmj0OZKc • 3 years ago


What to do in the case of an edit page. In an edit page both the dropdowns (parent and child) should be filled based on the prespecified values . Can
you please let me know
1△ ▽ • Reply • Share ›

F. Ali Ahmad > disqus_amKmj0OZKc • a year ago


In edit mode we need to load state as well as city on the basis of current employee record
Rest of the code is already there, that will be selected, see the dropdown binding m => m.State, m=>m.City
△ ▽ • Reply • Share ›

Bhavesh Patel • 4 years ago


good post. thank you.
1△ ▽ • Reply • Share ›

Sufiyan Ansari • 18 days ago • edited


Thanks for your important time to post this Article
This is really very use full for me
△ ▽ • Reply • Share ›

Satyendra Negi • 5 months ago


how to show saved value in same page, specially city drop down value. please tell us
△ ▽ • Reply • Share ›

Smitha • 2 years ago


Where is the 'States' coming from in ViewBag.StateList = db.States; ?
△ ▽ • Reply • Share ›

F. Ali Ahmad > Smitha • a year ago


That is coming from database states table
db is an object of someContext
△ ▽ • Reply • Share ›

Anonymous • 3 years ago


Why i click to select state, in city is doesn't display. and i debug, it notify "$(...).val(...).html is not a function"?
△ ▽ • Reply • Share ›

F. Ali Ahmad > Anonymous • a year ago


It means your jQuery file is not loaded properly.
△ ▽ • Reply • Share ›

Rehan • 3 years ago


action method in the controller is not being fired by your given code brother. sorry
△ ▽ • Reply • Share ›

Paris Pantigoso • 3 years ago


Here is the captures...


△ ▽ • Reply • Share ›

Marimar • 3 years ago • edited


I needed to change a few things // This is funtion on MVC5

@Html.DropDownList("CountryId", null, htmlAttributes: new { id = "Country", @class = "form-control" })

@Html.DropDownListFor(model => model.StateId, new SelectList(Enumerable.Empty<selectlistitem>(), "StateId", "StateName"), "Select State", new {
id = "StateId", @class = "form-control" })

@Html.DropDownListFor(model => model.CityId, new SelectList(Enumerable.Empty<selectlistitem>(), "CityId", "CityName"),"Select city",new { id =


"CityId", @class = "form-control" })

Json

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#Country').change(function () {
$('#StateId').html(null)
$
see more

△ ▽ • Reply • Share ›

FATKHUL KARIM > Marimar • 2 years ago


Thanks Marimar. It's work for me
△ ▽ • Reply • Share ›

Chourouk Hjaiej • 4 years ago


You can see this simple example of dropdownlist :

https://code.msdn.microsoft...
△ ▽ • Reply • Share ›

Peter Chang > Chourouk Hjaiej • 4 years ago


I have tables with identity primary key id. How can I use SQL table instead?
△ ▽ • Reply • Share ›

Advncesharp Mod > Peter Chang • 3 years ago

I used json data to show the demo, you can use any database and get data by using some kind of service like WebAPI, WebService,
WCF etc.
△ ▽ • Reply • Share ›

Peter Chang > Advncesharp • 3 years ago


Json works for now. May want to explore WebAPI later.
△ ▽ • Reply • Share ›

Pawel • 4 years ago • edited


Confusing is that you used "City" name twice. One time you created class with name City and later you called property integer with this name in class
"Employees". Due to this fact later is difficult to read JavaScripts. Despite that your tutorial is really useful. Thanks.
△ ▽ • Reply • Share ›

Thinkaboutit • 4 years ago


Very helpful. Thanks
△ ▽ • Reply • Share ›

Chinh Tran Nguyen • 4 years ago


It doesn't work on my side. Maybe I make something wrong. Have you tested it from your side mate?
△ ▽ • Reply • Share ›

Amar Salunke • 4 years ago


html.dropdownlist on change event ..i wana show data texbox using viewbag..how can do it ?? help me
△ ▽ • Reply • Share ›

Advncesharp Mod > Amar Salunke • 4 years ago

At the bottom of the page put your value into a variable on page load and use that latter on, see this

<script type="text/javascript">
var vbValue = @(ViewBag.someStringValue);
// now play with this variable easily
</script>
△ ▽ • Reply • Share ›

om • 4 years ago
could u upload the code source please
△ ▽ • Reply • Share ›

ALSO ON ADVANCESHARP.COM

ASP.NET Web API 2, Owin, OAuth, Bearer Token, Refresh Token Angularjs powerful paging on table and searching with delay and
with custom database demo
6 comments • a year ago 2 comments • 4 years ago
Mansur Haider — I am getting unsupported_grant_type error message naresh gorantla — i need to get the data from service from the database as
Avatarwhile call http://localhost:62670/token with postbody : { Avatarthe above Application.please suggest me. from a http service.
"userName" : "user1@dummy.com", $http.get("http://localhost/table2/mock.json").success(function(response){

Global error handling in angular 6 with HttpClient & interceptor AngularJS HTML5 mode reloading page not found solution
2 comments • a year ago 3 comments • 4 years ago
netalex — i will signal that your stackblitz has an incorrect dep, does'nt find Satish Somani — Its refreshing page continue.. not able to click on any link.
Avatarit in npm Avataras there is any suggestion how to fix it. I am using angular js ui routing with
MVC (.cshtml pages)

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy

Privacy Policy Legal About Us Contact Us Feedback Copyright © 2012 - 2019 AdvanceSharp.com All rights reserved

S-ar putea să vă placă și