Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Browse Tutorials

02 Intermediate

Custom Validation for Cascading Dropdownlist in MVC Razor

Custom Validation for Cascading Dropdownlist in MVC Razor

05 Mar 2024
Intermediate
182K Views
6 min read

This article will demonstrate, how to make and validate cascading dropdown list with in Asp.Net MVC4 Razor application using custom server-side and client-side validation. In this article, you will learn how set selected value with in Dropdown list in MVC Razor.

How to do it..

Follow the following steps for making and validating cascading dropdown list in mvc razor.

Step 1 : Design Model

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Text.RegularExpressions;
 namespace Mvc4_Validate_CascadingDropdown.Models
 { 
public class RegistrationModel 
{
 [Required(ErrorMessage = "Please Enter Email Address")]
 [Display(Name = "UserName (Email Address)")]
 [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
 public string UserName { get; set; }
 [Display(Name = "Country")]
 public Country Country { get; set; }
 [Display(Name = "City")]
 public City City { get; set; }
 [Required(ErrorMessage = "Please Enter Address")]
 [Display(Name = "Address")]
 [StringLength(200)]
 public string Address { get; set; }
 }
// IClientValidatable for client side Validation 
 public class MustBeSelectedAttribute : ValidationAttribute, IClientValidatable 
{
 public override bool IsValid(object value) {
 if (value == null || (int)value == 0)
 return false;
 else return true; 
} 
// Implement IClientValidatable for client side Validation 
public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
{ 
return new ModelClientValidationRule[] 
{
 new ModelClientValidationRule { ValidationType = "dropdown", ErrorMessage = this.ErrorMessage } }; 
} 
}
 public class Country
 { 
[MustBeSelectedAttribute(ErrorMessage = "Please Select Country")] 
public int? ID { get; set; }
 public string Name { get; set; }
 }
 public class City 
{ 
[MustBeSelectedAttribute(ErrorMessage = "Please Select City")] 
public int? ID { get; set; } 
public string Name { get; set; }
 public int? Country { get; set; } 
}
} 

Step 2: Design View based on Model

 @model Mvc4_Validate_CascadingDropdown.Models.RegistrationModel
@{ ViewBag.Title = "Validating Cascading Dropdownlist";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script type="text/jscript">
 //Custom jQuery validation unobtrusive script and adapters 
jQuery.validator.unobtrusive.adapters.add("dropdown", function (options) {
 if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
 options.rules["required"] = true;
 if (options.message) {
 options.messages["required"] = options.message;
 }
 }
 });
 $(function () {
 //get city list on changing of country dropdown list 
$('#Country_ID').change(function () {
 var id = $("#Country_ID :selected").val();
 if (id != "") {
 $.ajax({
 type: "GET",
 contentType: "application/json; charset=utf-8",
 url: '@Url.Action("CityList", "Home")',
 data: { "mCountry": id },
 dataType: "json",
 beforeSend: function () {
 //alert(id); 
},
 success: function (data) {
 var items = "";
 $.each(data, function (i, city) {
 items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
 });
 // Fill City Dropdown list 
$('#City_ID').html(items);
 },
 error: function (result) {
 alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
 }
 });
 }
 else {
 var items = '<option value="">Select</option>';
 $('#City_ID').html(items);
 }
 });
 });
</script>
<h2>Custom Validation for Cascading Dropdown List</h2>
@using (Html.BeginForm())
{
 <fieldset> <legend>Custom Validation for Cascading Dropdown List</legend> 
<ol> <li> 
@Html.LabelFor(m => m.UserName) 
@Html.TextBoxFor(m => m.UserName, new { maxlength = 50 }) 
@Html.ValidationMessageFor(m => m.UserName) </li> 
<li> 
@Html.LabelFor(m => m.Country) 
@Html.DropDownListFor(m => m.Country.ID, new SelectList(ViewBag.Country, "ID", "Name", ViewBag.SelCountry), new { style = "width:310px" }) 
@Html.ValidationMessageFor(m => m.Country.ID) 
</li> 
<li> 
@Html.LabelFor(m => m.City) 
@Html.DropDownListFor(m => m.City.ID, new SelectList(ViewBag.City, "ID", "Name", ViewBag.SelCity), new { style = "width:310px" }) 
@Html.ValidationMessageFor(m => m.City.ID) 
</li> 
<li>
 @Html.LabelFor(m => m.Address)
 @Html.TextAreaFor(m => m.Address, new { maxlength = 200 }) 
@Html.ValidationMessageFor(m => m.Address) 
</li> 
</ol>
 <input type="submit" value="Submit" /> 
</fieldset>
 } 

Design Controller Based on Model & View

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc4_Validate_CascadingDropdown.Models;
using System.Text.RegularExpressions;
namespace Mvc4_Validate_CascadingDropdown.Controllers {
 public class HomeController : Controller {
 #region Private Methods
 void BindCountry() {
 List<Country> lstCountry = new List<Country>
{
new Country { ID = null, Name = "Select" }, 
new Country { ID = 1, Name = "India" }, 
new Country { ID = 2, Name = "USA" } };
 ViewBag.Country = lstCountry;
 }
 //for server side
 void BindCity(int? mCountry) {
 try {
 if (mCountry != 0) 
{ 
//below code is only for demo, you can pick city from database
 int index = 1;
 List<City> lstCity = new List<City>{ 
new City { Country = 0, ID=null, Name = "Select" }, 
new City { Country = 1, ID=index++, Name = "Delhi" }, 
new City { Country = 1, ID=index++, Name = "Lucknow" }, 
new City { Country = 1, ID=index++, Name = "Noida" }, 
new City { Country = 1, ID=index++, Name = "Guragon" }, 
new City { Country = 1, ID=index++, Name = "Pune" }, 
new City { Country = 2, ID=index++, Name = "New-York" }, 
new City { Country = 2, ID=index++, Name = "California" },
 new City { Country = 2, ID=index++, Name = "Washington" }, 
new City { Country = 2, ID=index++, Name = "Vermont" }, };
 var city = from c in lstCity
 where c.Country == mCountry || c.Country == 0
 select c;
 ViewBag.City = city;
 }
 else {
 List<City> City = new List<City> { 
new City { ID = null, Name = "Select" } };
 ViewBag.City = City;
 }
 }
 catch (Exception ex) {
 }
 }
 #endregion
 //for client side using jquery
 public JsonResult CityList(int mCountry) {
 try {
 if (mCountry != 0) { 
//below code is only for demo, you can pick city from database
 int index = 1;
 List<City> lstCity = new List<City>{ 
new City { Country = 0, ID=null, Name = "Select" }, 
new City { Country = 1, ID=index++, Name = "Delhi" }, 
new City { Country = 1, ID=index++, Name = "Lucknow" }, 
new City { Country = 1, ID=index++, Name = "Noida" }, 
new City { Country = 1, ID=index++, Name = "Guragon" }, 
new City { Country = 1, ID=index++, Name = "Pune" }, 
new City { Country = 2, ID=index++, Name = "New-York" }, 
new City { Country = 2, ID=index++, Name = "California" }, 
new City { Country = 2, ID=index++, Name = "Washington" }, 
new City { Country = 2, ID=index++, Name = "Vermont" }, };
 var city = from c in lstCity
 where c.Country == mCountry || c.Country == 0
 select c;
 return Json(new SelectList(city.ToArray(), "ID", "Name"), JsonRequestBehavior.AllowGet);
 } 
}
 catch (Exception ex) {
 }
 return Json(null); 
}
 public ActionResult Index()
 {
 return View();
 }
 public ActionResult CustomDropdown()
 {
 BindCountry();
 BindCity(0);
 return View();
 }
 [HttpPost]
 public ActionResult CustomDropdown(RegistrationModel mRegister) 
{
 if (ModelState.IsValid) 
{
 return View("Completed");
 }
 else 
{
 ViewBag.SelCountry = mRegister.Country;
 BindCountry();
 ViewBag.SelCity = mRegister.City;
 if (mRegister.Country != null)
 BindCity(mRegister.Country.ID);
 else
 BindCity(null);
 return View(); 
}
 }
 }
} 

How it works..

It's time to run the project and let's see the result as shown below :

What do you think?

I hope you will enjoy the tricks while programming with MVC Razor. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this