asp.net mvc根据其他属性值使模型属性成为必需

时间:2018-05-10 18:33:54

标签: asp.net asp.net-mvc

我有一个模型,其中两个属性使用注释设置为必需。只有当第一个属性是特定值时,我才能如何制作第二个属性?我已经能够使用JQuery使其适用于空白表单,但问题在于我使用数据预填充表单时,它不识别第一个属性的值,因此不会设置其他属性是否必需。

以下是我的View和Javascript目前所做的事情......

...
<div class="form-group">
  @Html.LabelFor(x => x.Property1)
  @Html.DropDownListFor(x => x.Property1, Model.Prop1Values, "", new {@class ="form-group prop1"})
  @Html.ValidationMessageFor(x => x.Property1)
</div>
<div class="form-group">
  @Html.LabelFor(x => x.PropDependentOnProp1)
  @Html.DropDownListFor(x => x.PropDependentOnProp1, Model.Prop2Values, "", new {@class ="form-group prop2"})
  @Html.ValidationMessageFor(x => x.PropDependentOnProp1)
</div>
...
<script>
$(".prop1").on("change", function() {
var selected = $(this).find(":selected").val();
if(selected == "Y"){
  $(".prop2").rules('add', {
    required: true
  });
} else {
  $(".prop2").rules('add', {
    required: false
  });
}
</script>

这适用于新表单,但在模型中预先填充数据时,验证更改在Property1更改后才会生效。我试图在$(document).ready中将类似的逻辑放在上面,但是不能改变未定义的属性&#39;设置&#39;&#34;。我找到了一个可能的解决方法here的链接,以首先实例化验证器,但这会删除我需要的其他属性的所有验证,并且不使用Html Helper方法中的验证<span>标记。

1 个答案:

答案 0 :(得分:0)

您可以使用验证上下文实现自己的验证属性并访问模型。以下代码来自dotnetmentors,可以让您了解如何根据需要对其进行修改

using System.ComponentModel.DataAnnotations;

namespace FirstMVC.Models
{
    public class ValidLastDeliveryDate : ValidationAttribute
    {
        protected override ValidationResult 
                IsValid(object value, ValidationContext validationContext)
        {
            var model = (Models.Customer)validationContext.ObjectInstance;
            DateTime _lastDeliveryDate = Convert.ToDateTime(value);
            DateTime _dateJoin = Convert.ToDateTime(model.JoinDate);  

            if (_dateJoin > _lastDeliveryDate)
            {
                return new ValidationResult
                    ("Last Delivery Date can not be less than Join date.");                
            }
            else if (_lastDeliveryDate > DateTime.Now)
            {
                return new ValidationResult
                    ("Last Delivery Date can not be greater than current date.");                
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
}
相关问题