【问题标题】:Make a required field if the other field has value如果其他字段有值,请填写必填字段
【发布时间】:2015-05-28 15:50:06
【问题描述】:

我有这些变量:

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 的文本不是“-- Select --”,并且我想进行该验证(我在控制器,使用 JavaScript 检查特定卖家(老板)的admissionDate 日期,我该怎么做?

【问题讨论】:

  • “工作正常”的东西有什么问题?
  • 我不是在询问脚本 1,我只是在显示我的代码,我正在寻找脚本 2 的解决方案和一个脚本示例,以使用 JS 进行验证(在控制器中)。你现在明白了吗?顺便说一句,我会编辑..

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


【解决方案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"
        }
    }
});

【讨论】:

  • 我要求进行客户端验证,无论如何,ModelState.IsValid 会自动调用这个类“MyViewModel”吗?你看过我的剧本2吗?我错过了什么? [如果 BossId 有值,则需要 headShip].. 谢谢。
  • 是的,ModelState 会自动得到MyViewModels Validate 方法的结果。
  • 你能发布你的视图模型类吗?
  • 我创建了一个类,正如你在这里发布的,命名为 MyViewModel,我只有模型、控制器和视图,现在是这个新类。
  • 这个新类是你的模型,应该连接到你的视图和控制器。不应该有两个模型。
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
相关资源
最近更新 更多