【发布时间】:2016-12-18 16:34:13
【问题描述】:
我想根据另一个属性的值使用数据注释来验证一个属性。
我有一个人模型--
public class People
{
[DisplayName("Your Name")]
[Required]
public string Name { get; set; }
[Required]
public string Gender { get; set; }
[DisplayName("Your Age")]
[Required]
// Another Attribute here for my custom validation
public int Age { get; set; }
}
和索引:
public ActionResult Index()
{
IList<SelectListItem> types = new List<SelectListItem>();
types.Add(new SelectListItem() { Text = "Male", Value = "M" });
types.Add(new SelectListItem() { Text = "Female", Value = "F" });
ViewBag.ItemTypes = types;
return View();
}
'Gender' 绑定到一个下拉列表,并基于所选的 Gender 我要验证 'Age' 属性。
- 如果选择男性,则年龄范围必须介于 22 到 60 岁之间。
- 如果选择了女性,则年龄范围必须介于 18 到 58 岁之间。
必须有一个自定义验证属性,但我无法弄清楚。
我的观点:
@using (Html.BeginForm("Index", "Test", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TimeRecord</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Gender, (IEnumerable<SelectListItem>)ViewBag.ItemTypes, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Age, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Age, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
【问题讨论】:
-
您需要编写自己的条件验证属性。请参阅 The Complete Guide To Validation In ASP.NET MVC 3 - Part 2 以获得为客户端和服务器端验证创建验证属性的良好指南
标签: asp.net-mvc