如何创建具有所需验证的 ASP.Net MVC DropDownList
Posted
技术标签:
【中文标题】如何创建具有所需验证的 ASP.Net MVC DropDownList【英文标题】:How to create ASP.Net MVC DropDownList with required validation 【发布时间】:2017-05-21 14:59:25 【问题描述】:我正在使用 mvc 5。我正在使用 ORM 从数据库中加载数据,并从控制器中填写一个下拉列表,如下所示。
ViewBag.Country_id = new SelectList(_db.Countries, "Country_id", "Description");
因为我首先想要一个空字段,所以我在我的 html 中这样做。
<div class="form-group">
@Html.LabelFor(model => model.Countries, "Country", htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.DropDownList("Country_id", null, htmlAttributes: new @class = "form-control" , optionLabel: "Choose a Country")
@Html.ValidationMessageFor(model => model.Country_id, "", new @class = "text-danger" )
</div>
</div>
空选项的值为“0”。
我想验证用户选择了一个国家,所以我添加了这个验证
[Required,Range(1, int.MaxValue, ErrorMessage = "Error: Must Choose a Country")]
public int Country_id get; set;
问题是永远不会让我出错。始终为“0”且未发生验证。
我错过了什么?
【问题讨论】:
【参考方案1】:使用 DropDownList 的方法很少。我个人喜欢使用 Strongly-Type ViewModel 而不是 ViewBag。 p>
屏幕截图
在未选择国家的情况下单击提交按钮时显示验证消息。
实体
public class Country
public int Country_id get; set;
public string Description get; set;
型号
public class CountryViewModel
[Display(Name = "Country")]
[Required(ErrorMessage = "0 is required.")]
public int SelectedCountryId get; set;
public IList<SelectListItem> AvailableCountries get; set;
public CountryViewModel()
AvailableCountries = new List<SelectListItem>();
控制器
public class HomeController : Controller
public ActionResult Create()
var countries = GetCountries();
var model = new CountryViewModel AvailableCountries = countries;
return View(model);
[HttpPost]
public async Task<ActionResult> Create(CountryViewModel countryViewModel)
if (ModelState.IsValid)
int countryId = countryViewModel.SelectedCountryId;
// Do something
// If we got this far, something failed. So, redisplay form
countryViewModel.AvailableCountries = GetCountries();
return View(countryViewModel);
public IList<SelectListItem> GetCountries()
// This comes from database.
var _dbCountries = new List<Country>
new Country Country_id = 1, Description = "USA",
new Country Country_id = 2, Description = "UK",
new Country Country_id = 3, Description = "Canada",
;
var countries = _dbCountries
.Select(x => new SelectListItem Text = x.Description, Value = x.Country_id.ToString())
.ToList();
countries.Insert(0, new SelectListItem Text = "Choose a Country", Value = "");
return countries;
查看
@model DemoMvc.Models.CountryViewModel
@
Layout = null;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
<h2>Create</h2>
@using (Html.BeginForm())
<div class="form-group">
@Html.LabelFor(model => model.SelectedCountryId,
new @class = "control-label col-md-2")
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedCountryId,
Model.AvailableCountries, new @class = "form-control")
@Html.ValidationMessageFor(model => model.SelectedCountryId,
"", new @class = "text-danger")
</div>
</div>
<input type="submit" value="Submit"/>
</body>
</html>
【讨论】:
【参考方案2】:首先,您无法使用您正在使用的DropDownList()
的重载来获得任何客户端验证。您需要为绑定到的属性和SelectList
使用不同的名称。将控制器代码更改为(比如说)
ViewBag.CountryList = new SelectList(_db.Countries, "Country_id", "Description");
并将模型属性属性更改为(删除RangeAttribute
)
[Required(ErrorMessage = "Error: Must Choose a Country")]
public int Country_id get; set;
然后在视图中使用生成null
标签选项的重载
@Html.DropDownListFor(m => m.Country_id, (SelectList)ViewBag.CountryList, "Choose a Country", new @class = "form-control" )
如果用户提交表单时选择了第一个(“选择国家”)选项,则会显示验证错误。
旁注:建议您使用具有属性public IEnumerable<SelectListItem> CountryList get; set;
而不是ViewBag
的视图模型(视图变为@Html.DropDownListFor(m => m.Country_id, Model.CountryList, "Choose a Country", new @class = "form-control" )
【讨论】:
【参考方案3】:模型类
[Display(Name = "Program")]
[Required, Range(1, int.MaxValue, ErrorMessage = "Select Program")]
public string Programid get; set;
查看
@Html.DropDownListFor(Model=>Model.Programid,(IEnumerable<SelectListItem>)ViewBag.Program, new @id = "ddlProgram")
【讨论】:
是的...当您插入一个显示“--Select--”的项目时,您需要该范围。【参考方案4】:对于 .net core 而不是 @Html.ValidationMessageFor(...
使用
剃须刀 cshtml
<span asp-validation-for="SelectedCountryId" class="text-danger"></span>
模型 poco
[Required(ErrorMessage = "Country is required.")]
public int SelectedCountryId get; set;
【讨论】:
今天回答!核心 ASP 已经走过了漫长的道路。以上是关于如何创建具有所需验证的 ASP.Net MVC DropDownList的主要内容,如果未能解决你的问题,请参考以下文章
ASP.Net MVC 5 Html.BeginForm onsubmit 和具有所需属性的模型