Dropdownlist验证是否选择
来源:互联网 发布:js密码和确认密码校验 编辑:程序博客网 时间:2024/05/17 03:38
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 :
出处:http://www.dotnet-tricks.com/Tutorial/mvc/HL53191212-Custom-Validation-for-Cascading-Dropdownlist-in-MVC-Razor.html
0 0
- Dropdownlist验证是否选择
- 根据radiobutton的选择决定dropdownlist是否禁用
- Jquery.Validate验证CheckBoxList,RadioButtonList,DropDownList是否选中
- Jquery.Validate验证CheckBoxList,RadioButtonList,DropDownList是否选中
- 验证DropDownList
- 每日学习总结:DropDownList是否已选择验证、存储过程参数为sql字符串问题、将截断字符串或二进制数据。\r\n语句已终止
- 验证控件验证DropDownList
- JS验证一-CheckBoxList是否选择
- DropDownList选择问题
- Ajax Dropdownlist级联选择
- dropdownlist添加请选择
- DropDownList 加上请选择
- CustomValidator客户端验证DropDownList
- 验证dropdownlist必选
- 关于DropDownList选择值问题
- dropdownlist 默认填充 --请选择---
- DropDownList中“请选择”变色
- DropdownList添加下拉"请选择"
- 使用android SpannableStringBuilder实现图文混排源码
- Tag system implementation
- Summary of problems when coding
- 统计一个文件中的字符数,单词数,制表符。
- 自动换行LinearLayout
- Dropdownlist验证是否选择
- android 修改文本选中默认样式
- 进程与线程的一个简单解释
- 建立一个程序,写2个线程,同时对一个文件里面写入字符串,另外一个程序读取输出在控制台,保证读取的实时性。
- Cocos2d-x 常用语句
- 安卓带点击效果的圆角button
- 世界坐标转UGUI屏幕坐标
- Linux Advance--标准I/O的效率
- 合入mpls的情况-netlink失灵了