суббота, 12 января 2013 г.

Custom Validation for Cascading Dropdownlist in MVC Razor


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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Web.Mvc;
  7. using System.Text.RegularExpressions;
  8. namespace Mvc4_Validate_CascadingDropdown.Models
  9. {
  10. public class RegistrationModel
  11. {
  12. [Required(ErrorMessage = "Please Enter Email Address")]
  13. [Display(Name = "UserName (Email Address)")]
  14. [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
  15. public string UserName { get; set; }
  16. [Display(Name = "Country")]
  17. public Country Country { get; set; }
  18. [Display(Name = "City")]
  19. public City City { get; set; }
  20. [Required(ErrorMessage = "Please Enter Address")]
  21. [Display(Name = "Address")]
  22. [StringLength(200)]
  23. public string Address { get; set; }
  24. }
  25. // IClientValidatable for client side Validation
  26. public class MustBeSelectedAttribute : ValidationAttribute, IClientValidatable
  27. {
  28. public override bool IsValid(object value) {
  29. if (value == null || (int)value == 0)
  30. return false;
  31. else return true;
  32. }
  33. // Implement IClientValidatable for client side Validation
  34. public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  35. {
  36. return new ModelClientValidationRule[]
  37. {
  38. new ModelClientValidationRule { ValidationType = "dropdown", ErrorMessage = this.ErrorMessage } };
  39. }
  40. }
  41. public class Country
  42. {
  43. [MustBeSelectedAttribute(ErrorMessage = "Please Select Country")]
  44. public int? ID { get; set; }
  45. public string Name { get; set; }
  46. }
  47. public class City
  48. {
  49. [MustBeSelectedAttribute(ErrorMessage = "Please Select City")]
  50. public int? ID { get; set; }
  51. public string Name { get; set; }
  52. public int? Country { get; set; }
  53. }
  54. }

Step 2: Design View based on Model

  1. @model Mvc4_Validate_CascadingDropdown.Models.RegistrationModel
  2. @{ ViewBag.Title = "Validating Cascading Dropdownlist";
  3. }
  4. Custom Validation for Cascading Dropdown List
  • @using (Html.BeginForm())
  • {
  • Custom Validation for Cascading Dropdown List
    1. @Html.LabelFor(m => m.UserName)
    2. @Html.TextBoxFor(m => m.UserName, new { maxlength = 50 })
    3. @Html.ValidationMessageFor(m => m.UserName)
    4. @Html.LabelFor(m => m.Country)
    5. @Html.DropDownListFor(m => m.Country.ID, new SelectList(ViewBag.Country, "ID", "Name", ViewBag.SelCountry), new { style = "width:310px" })
    6. @Html.ValidationMessageFor(m => m.Country.ID)
    7. @Html.LabelFor(m => m.City)
    8. @Html.DropDownListFor(m => m.City.ID, new SelectList(ViewBag.City, "ID", "Name", ViewBag.SelCity), new { style = "width:310px" })
    9. @Html.ValidationMessageFor(m => m.City.ID)
    10. @Html.LabelFor(m => m.Address)
    11. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
    12. @Html.ValidationMessageFor(m => m.Address)
    13. type="submit" value="Submit" />
    14. }
    15. Design Controller Based on Model & View

      1. using System;
      2. using System.Collections.Generic;
      3. using System.Linq;
      4. using System.Web;
      5. using System.Web.Mvc;
      6. using Mvc4_Validate_CascadingDropdown.Models;
      7. using System.Text.RegularExpressions;
      8. namespace Mvc4_Validate_CascadingDropdown.Controllers {
      9. public class HomeController : Controller {
      10. #region Private Methods
      11. void BindCountry() {
      12. List lstCountry = new List
      13. {
      14. new Country { ID = null, Name = "Select" },
      15. new Country { ID = 1, Name = "India" },
      16. new Country { ID = 2, Name = "USA" } };
      17. ViewBag.Country = lstCountry;
      18. }
      19. //for server side
      20. void BindCity(int? mCountry) {
      21. try {
      22. if (mCountry != 0)
      23. {
      24. //below code is only for demo, you can pick city from database
      25. int index = 1;
      26. List lstCity = new List{
      27. new City { Country = 0, ID=null, Name = "Select" },
      28. new City { Country = 1, ID=index++, Name = "Delhi" },
      29. new City { Country = 1, ID=index++, Name = "Lucknow" },
      30. new City { Country = 1, ID=index++, Name = "Noida" },
      31. new City { Country = 1, ID=index++, Name = "Guragon" },
      32. new City { Country = 1, ID=index++, Name = "Pune" },
      33. new City { Country = 2, ID=index++, Name = "New-York" },
      34. new City { Country = 2, ID=index++, Name = "California" },
      35. new City { Country = 2, ID=index++, Name = "Washington" },
      36. new City { Country = 2, ID=index++, Name = "Vermont" }, };
      37. var city = from c in lstCity
      38. where c.Country == mCountry || c.Country == 0
      39. select c;
      40. ViewBag.City = city;
      41. }
      42. else {
      43. List City = new List {
      44. new City { ID = null, Name = "Select" } };
      45. ViewBag.City = City;
      46. }
      47. }
      48. catch (Exception ex) {
      49. }
      50. }
      51. #endregion
      52. //for client side using jquery
      53. public JsonResult CityList(int mCountry) {
      54. try {
      55. if (mCountry != 0) {
      56. //below code is only for demo, you can pick city from database
      57. int index = 1;
      58. List lstCity = new List{
      59. new City { Country = 0, ID=null, Name = "Select" },
      60. new City { Country = 1, ID=index++, Name = "Delhi" },
      61. new City { Country = 1, ID=index++, Name = "Lucknow" },
      62. new City { Country = 1, ID=index++, Name = "Noida" },
      63. new City { Country = 1, ID=index++, Name = "Guragon" },
      64. new City { Country = 1, ID=index++, Name = "Pune" },
      65. new City { Country = 2, ID=index++, Name = "New-York" },
      66. new City { Country = 2, ID=index++, Name = "California" },
      67. new City { Country = 2, ID=index++, Name = "Washington" },
      68. new City { Country = 2, ID=index++, Name = "Vermont" }, };
      69. var city = from c in lstCity
      70. where c.Country == mCountry || c.Country == 0
      71. select c;
      72. return Json(new SelectList(city.ToArray(), "ID", "Name"), JsonRequestBehavior.AllowGet);
      73. }
      74. }
      75. catch (Exception ex) {
      76. }
      77. return Json(null);
      78. }
      79. public ActionResult Index()
      80. {
      81. return View();
      82. }
      83. public ActionResult CustomDropdown()
      84. {
      85. BindCountry();
      86. BindCity(0);
      87. return View();
      88. }
      89. [HttpPost]
      90. public ActionResult CustomDropdown(RegistrationModel mRegister)
      91. {
      92. if (ModelState.IsValid)
      93. {
      94. return View("Completed");
      95. }
      96. else
      97. {
      98. ViewBag.SelCountry = mRegister.Country;
      99. BindCountry();
      100. ViewBag.SelCity = mRegister.City;
      101. if (mRegister.Country != null)
      102. BindCity(mRegister.Country.ID);
      103. else
      104. BindCity(null);
      105. return View();
      106. }
      107. }
      108. }
      109. }

      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.

      Комментариев нет: