如何创建需要验证的 ASP.Net MVC DropDownList
How to create ASP.Net MVC DropDownList with required validation
我使用 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”且未发生验证。
我缺了什么?
使用 DropDownList 的方法很少。我个人喜欢使用强类型ViewModel而不是ViewBag.
屏幕截图
在未选择国家/地区的情况下单击提交按钮时显示验证消息。
实体
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>
首先,您无法使用您正在使用的 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" })
如果用户提交表单时选择了第一个 ("Choose a Country") 选项,将显示验证错误。
旁注:建议您使用 属性 public IEnumerable<SelectListItem> CountryList { get; set; }
而不是 ViewBag
的视图模型(并且视图变为 @Html.DropDownListFor(m => m.Country_id, Model.CountryList, "Choose a Country", new { @class = "form-control" })
型号Class
[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"})
对于.net core而不是@Html.ValidationMessageFor(...
使用
razor cshtml
<span asp-validation-for="SelectedCountryId" class="text-danger"></span>
型号poco
[Required(ErrorMessage = "Country is required.")]
public int SelectedCountryId { get; set; }
我使用 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”且未发生验证。
我缺了什么?
使用 DropDownList 的方法很少。我个人喜欢使用强类型ViewModel而不是ViewBag.
屏幕截图
在未选择国家/地区的情况下单击提交按钮时显示验证消息。
实体
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>
首先,您无法使用您正在使用的 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" })
如果用户提交表单时选择了第一个 ("Choose a Country") 选项,将显示验证错误。
旁注:建议您使用 属性 public IEnumerable<SelectListItem> CountryList { get; set; }
而不是 ViewBag
的视图模型(并且视图变为 @Html.DropDownListFor(m => m.Country_id, Model.CountryList, "Choose a Country", new { @class = "form-control" })
型号Class
[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"})
对于.net core而不是@Html.ValidationMessageFor(...
使用
razor cshtml
<span asp-validation-for="SelectedCountryId" class="text-danger"></span>
型号poco
[Required(ErrorMessage = "Country is required.")]
public int SelectedCountryId { get; set; }