Dropdownlist验证是否选择

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. <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
  5. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
  6. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
  7. <script type="text/jscript">
  8. //Custom jQuery validation unobtrusive script and adapters
  9. jQuery.validator.unobtrusive.adapters.add("dropdown", function (options) {
  10. if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
  11. options.rules["required"] = true;
  12. if (options.message) {
  13. options.messages["required"] = options.message;
  14. }
  15. }
  16. });
  17. $(function () {
  18. //get city list on changing of country dropdown list
  19. $('#Country_ID').change(function () {
  20. var id = $("#Country_ID :selected").val();
  21. if (id != "") {
  22. $.ajax({
  23. type: "GET",
  24. contentType: "application/json; charset=utf-8",
  25. url: '@Url.Action("CityList", "Home")',
  26. data: { "mCountry": id },
  27. dataType: "json",
  28. beforeSend: function () {
  29. //alert(id);
  30. },
  31. success: function (data) {
  32. var items = "";
  33. $.each(data, function (i, city) {
  34. items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
  35. });
  36. // Fill City Dropdown list
  37. $('#City_ID').html(items);
  38. },
  39. error: function (result) {
  40. alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
  41. }
  42. });
  43. }
  44. else {
  45. var items = '<option value="">Select</option>';
  46. $('#City_ID').html(items);
  47. }
  48. });
  49. });
  50. </script>
  51. <h2>Custom Validation for Cascading Dropdown List</h2>
  52. @using (Html.BeginForm())
  53. {
  54. <fieldset> <legend>Custom Validation for Cascading Dropdown List</legend>
  55. <ol> <li>
  56. @Html.LabelFor(m => m.UserName)
  57. @Html.TextBoxFor(m => m.UserName, new { maxlength = 50 })
  58. @Html.ValidationMessageFor(m => m.UserName) </li>
  59. <li>
  60. @Html.LabelFor(m => m.Country)
  61. @Html.DropDownListFor(m => m.Country.ID, new SelectList(ViewBag.Country, "ID", "Name", ViewBag.SelCountry), new { style = "width:310px" })
  62. @Html.ValidationMessageFor(m => m.Country.ID)
  63. </li>
  64. <li>
  65. @Html.LabelFor(m => m.City)
  66. @Html.DropDownListFor(m => m.City.ID, new SelectList(ViewBag.City, "ID", "Name", ViewBag.SelCity), new { style = "width:310px" })
  67. @Html.ValidationMessageFor(m => m.City.ID)
  68. </li>
  69. <li>
  70. @Html.LabelFor(m => m.Address)
  71. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
  72. @Html.ValidationMessageFor(m => m.Address)
  73. </li>
  74. </ol>
  75. <input type="submit" value="Submit" />
  76. </fieldset>
  77. }

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<Country> lstCountry = new List<Country>
  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<City> lstCity = new List<City>{
  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> City = new List<City> {
  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<City> lstCity = new List<City>{
  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 :

   


出处:http://www.dotnet-tricks.com/Tutorial/mvc/HL53191212-Custom-Validation-for-Cascading-Dropdownlist-in-MVC-Razor.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值