2012-02-21 30 views

回答

8

可以使用实现对服务器端验证IValidatableObject(从System.ComponentModel.DataAnnotations命名空间)您的视图模型:

public class AClass : IValidatableObject 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public string SecondName { get; set; } 
     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
     { 
      if((!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName))) 
       yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"}); 
     } 
    } 

现在,它使当然,如果Name和SecondName都设置了,或者null,那么model是有效的,否则它不是。

+0

仅供参考,我建议在使用验证摘要时不要返回验证结果中的字段。如果您返回验证结果中的两个字段,则验证摘要将包含两条消息,而不是预期的单条消息。 – 2015-03-31 17:22:05

+0

你可以包含一些代码来说明如何使用它来注释类属性吗? – niico 2017-02-24 17:35:03

0

您可以使用jQuery,像这样:

$("input[x2]").hide(); 
    $("input[x1]").keypress(function() { 
      var textValue = ("input[x1]").val(); 
     if(textValue) 
         $("input[x2]").show(); 
     }) 
相关问题