2012-02-21 31 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(); 
     }) 
相關問題