我有这些变量:
public int? BossId { get; set; }
public DateTime? HeadShipDate { get; set; }
我的看法:
<div class="form-group">
@Html.LabelFor(model => model.BossId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("BossId", null, "-- Select --", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BossId, "", new { @class = "text-danger" })
</div>
</div>
<div id="divDate" class="form-group">
@Html.LabelFor(model => model.HeadShipDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HeadShipDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.HeadShipDate, "", new { @class = "text-danger" })
</div>
</div>
脚本(如果 BossId 有值,我试图将其设置为必需的):
<script type="text/javascript">
HeadShipDate: {
required: {
depends: function(element){
return $("#BossId").text() != '-- Select --';
}
}
}
</script>
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Acronym,Percentage,BossId,HeadShipDate")] Department department)
{
Seller boss = db.Sellers.Find(department.BossId);
if (boss.AdmissionDate > department.HeadShipDate)
ModelState.AddModelError(string.Empty, "Headship Date (" + department.HeadShipDate.Value.ToShortDateString() + ") must be greater than the Admission Date (" + boss.AdmissionDate.ToShortDateString() + ") of boss");
else if (ModelState.IsValid)
{
boss.DeptId = department.Id;
db.Departments.Add(department);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.BossId = new SelectList(SellersNonBosses(), "Id", "Name", department.BossId);
return View(department);
}
如果 BossId 有一个值,在其他作品中,如果 DropDownList 的文本不是“-- Select --”,并且我想进行该验证(我在 Controller ,使用 JavaScript 检查领导日期和特定卖家(老板)的入场日期),我该如何做到这一点?
最佳答案
实现IValidatableObject在您的 View 模型上可以更好地控制像这样的临时验证规则。
示例
public class Department : IValidatableObject
{
public int? BossId { get; set; }
public DateTime? HeadShipDate { get; set; }
...
public IEnumerable<ValidationResult> Validate( ValidationContext validationContext )
{
if( BossId.HasValue && !HeadShipDate.HasValue )
{
yield return new ValidationResult( "HeadShipDate is required if BossId is selected.", new[] { "HeadShipDate" } );
}
}
}
那么您只需在 Controller 操作中检查 ModelState.IsValid
即可。
注意:这仅将服务器端验证应用于 ModelState。如果您还需要客户端验证,则需要实现一个 Javascript 函数,该函数在提交表单之前执行类似的操作。
示例:
$('form').validate({
rules: {
HeadShipDate: {
required: {
depends: function (element) {
return $("#BossId").val() != '';
}
}
}
},
messages: {
HeadShipDate: {
required: "Please specify the Headship Date"
}
}
});
关于javascript - 如果其他字段有值(value),则创建必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30511415/