Dropdownlist验证是否选择
2015-11-24 15:16
375 查看
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.
Follow the following steps for making and validating cascading dropdown list in mvc razor.
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
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 :出处:http://www.dotnet-tricks.com/Tutorial/mvc/HL53191212-Custom-Validation-for-Cascading-Dropdownlist-in-MVC-Razor.html
相关文章推荐
- 使用 Screen 创建并管理多个 shell
- Legolas工业自动化平台案例 —— 水源地自动化监控系统
- linux下安装mysql以及错误解决方案
- tomcat-部署
- Linux下压缩某个文件夹(文件夹打包)
- 微软算法100道题-------输入两个整数序列。其中一个序列表示栈的push顺序, 判断另一个序列有没有可能是对应的pop顺序。
- tomcat如何配置环境变量
- Linux下python升级至2.7步骤
- Hadoop(2.7.0)伪分布式环境CentOS(7.0 64位)配置
- 使用 PAM 集成 OpenLDAP 实现 Linux 统一管理系统用户
- linux命令行任务管理
- Mahout解决异常Not implemented by the DistributedFileSystem FileSystem implementation
- ofbiz配置文件[widget.properties]解析
- Nginx 配置 location 总结及 rewrite 规则写法
- (二)linux下ping不通的解决方法
- linux查看目录大小
- 【转载】OpenMAXIL介绍与其体系
- iOS开源程序下载网站
- Centos6.7 ELK日志系统部署
- Win7+花生壳6.0+tomcat打做自己的web服务器(搭建自己的网站)(参考)