如果其他字段具有值

时间:2015-05-28 15:50:06

标签: javascript c# jquery controller asp.net-mvc-5.2

我有这些变量:

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>

控制器:

[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);
 }

我想让HeadShipDate必填字段IF BossId有一个值,在其他工作中,如果DropDownList的文本不是“ - 选择 - ”,并且我想进行验证(我做的那个条件)控制器,使用JavaScript检查该特定卖家(Boss)的录取日期,我该如何制作?

1 个答案:

答案 0 :(得分:1)

在您的视图模型上实现IValidatableObject可以更好地控制像这样的临时验证规则。

实施例

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" } );
        }
    }
}

然后,您只需要在控制器操作中检查ModelState.IsValid

注意:这仅将服务器端验证应用于ModelState。如果您还需要客户端验证,则需要在提交表单之前实现类似功能的Javascript函数。

示例:

$('form').validate({
    rules: {
        HeadShipDate: {
            required: {
                depends: function (element) {
                    return $("#BossId").val() != '';
                }
            }
        }
    },
    messages: {
        HeadShipDate: {
            required: "Please specify the Headship Date"
        }
    }
});