Custom Validation for Cascading Dropdownlist in MVC Razor

Custom Validation for Cascading Dropdownlist in MVC Razor

23 Mar 2024
Intermediate
182K Views
8 min read

Cascading Dropdownlist in MVC Razor: An Overview

The Asp.Net MVC4 Razor application uses custom server-side and client-side validation. In this MVC Tutorial, we will explore more about Custom Validation for Cascading Dropdownlist in MVC Razorwhich will include setting the selected value to the dropdown list in MVC Razor, validating cascading dropdownlist in mvc4 and, cascading dropdown list with jQuery in mvc razor. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.

Setting the selected value to the dropdown list

Database:

So firstly, DropDownList will be populated from Database using the Entity Framework and then the DropDownList item to be shown as Selected will be set in Model and finally, the Model will be used to populate the DropDownList in ASP.Net MVC Razor. Let's elaborate on this in C# Compiler.

Step 1: Design Model

public class MyViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable Categories { get; set; } 
}

Step 2: Populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn)
{
    var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
    var categories = (from b in dc.dms_NewsCategories select b).ToList();

    var model = new MyViewModel
    {
        SelectedCategoryId = dsn.NewsCategoriesID,
        Categories = categories.Select(x => new SelectListItem
        {
            Value = x.NewsCategoriesID.ToString(),
            Text = x.NewsCategoriesName
        })
    };
    return View(model);
}

Step 3: Use the strongly typed DropDownListFor helper

@model MyViewModel

@Html.DropDownListFor(
    x => x.SelectedCategoryId,
    Model.Categories
)  

Validating cascading dropdown list

Follow the following steps for making and validating the 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 the 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>
 }   

Step-3 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(); 
}
 }
 }
}    

Output

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

Conclusion:

So in this article, we have learned the validating cascading dropdown list in mvc4 while extending the ASP.NET MVC framework. I hope you enjoyed learning these concepts while programming with Asp.Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Level up your career in MVC with our ASP.Net Core Certification.

FAQs

Q1. How to add validation for DropDownList in MVC?

By applying “ValidationRules” and “ValidationMessage” to the DropDownList.

Q2. How do I add validation to DropDownList?

The EditForm component validates all data annotation rules using the DataAnnotationsValidator component

Q3. How to add items in DropDownList using JavaScript?

Select add() Method. The add() method is used to add an option to a drop-down list.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification Training May 26 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training May 26 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification Training Jun 14 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core (Project) Jun 22 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

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