1
我需要對文本框和下拉菜單執行驗證,只有當這兩個值都爲空時纔會觸發,並且在其中一個值爲空時不執行任何操作。我將如何實現它?我是否需要創建自定義驗證器?下面是我的模型和視圖 型號ASP MVC驗證
public class CustomValidators
{
[Required]
[Required(ErrorMessage = "State Required")]
public string drpStateId { set; get; }
public System.Web.Mvc.SelectList drpState { set; get; }
[Required(ErrorMessage ="Region Required")]
public string txtRegion { set; get; }
}
查看
@model InterviewTest.Models.CustomValidators
@{
ViewBag.Title = "Custom Validator";
Layout = "~/Views/_Layout.cshtml";
}
<p>@Html.ActionLink("< Back", "Index")</p>
@using (Html.BeginForm("CustomValidatorPost"))
{
@Html.ValidationSummary()
<div class="container-fluid">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
@Html.DropDownListFor(c => c.drpStateId, Model.drpState, "", new { @class = "form-control" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
@Html.TextBoxFor(x => Model.txtRegion, new { @class = "form-control" })
@*<input type="text" id="txtRegion" name="txtRegion" class="form-control" />*@
</div>
</div>
<div class="col-sm-3">
<button type="submit" name="btnSubmit" id="btnSubmit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}
考慮一個適用於您的txtRegio的[foolproof](http://foolproof.codeplex.com/)'[RequiredIfNotEmpty(「drpStateId」)]'屬性n'屬性(和類似的應用於'drpStateId'屬性,並刪除'[Required]'屬性) –
@StephenMuecke當我試圖提交作品時,兩者都是空的 – aj12
對不起,誤解了你的要求。爲此,您需要編寫自己的自定義驗證屬性 - [ASP.NET MVC 3中的驗證完整指南 - 第2部分](http://www.devtrends.co.uk/blog/the-complete-引導到驗證功能於asp.net-MVC -3-部分-2) –