如果其他字段有值,则创建必填字段

本文关键字:字段 创建 其他 如果 | 更新日期: 2023-09-27 17:50:59

我有这些变量:

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必需字段如果BossId有一个值,在其他作品中,如果DropDownList的文本不是"——选择——",并且我想使验证(我在控制器中的条件,检查headship日期与特定卖家(Boss)的admissionDate))与JavaScript,我怎么能做到这一点?

如果其他字段有值,则创建必填字段

在视图模型上实现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"
        }
    }
});