別のプロパティの値に基づいてデータアノテーションを使用してプロパティを検証する必要があります。MVCで選択した値をドロップダウンしてカスタム検証を行います
私は人々が
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; }
}
をmodel--とキーワードがあります。
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();
}
「性別」が、私は「年齢を検証するドロップダウンリストにバインドされ、選択した性別に基づいています'プロパティ。男性が選択されている場合は
- その後、年齢範囲は、カスタムが存在しなければならない女性が選択されている場合は、年齢範囲は18と58
の間でなければなりません22と60
マイビュー:
@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>
}
あなたがあなた自身の条件の検証属性を記述する必要があります。 [ASP.NET MVC 3での検証の完全ガイド - 第2部](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc- 3部-2)、クライアント側とサーバー側の両方の検証用の検証属性を作成するための良いガイドです。 –