2016-07-26 8 views
0

現在、既存の「リモート」アトリビュートにアトリビュート・シミュレータを作成しています。クライアント側の検証は、javasciptが入力が有効であることを確認するアクションを呼び出すことで(これは私たちのデータベースでもあります)前進しています。問題はサーバー側の検証になるときです。私はそのアクションをどのように呼び出すことができますか? 「リモート側の」属性は「サーバ側の検証はしません」ので助けにはなりません検証アトリビュートから指定されたアクションを呼び出す

クライアント側のコードは正しく動作しているので、showは表示されません。

属性

[AttributeUsage(AttributeTargets.Property)] 
public class AjaxValidation : Attribute, IModelValidator { 

    private readonly string _action; 
    private readonly string _area; 
    private readonly string _controller; 

    public AjaxValidation(string action, string controller = null, string area = null) { 
     _action = action; 
     _area = area; 
     _controller = controller; 
    } 

    public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context) { 

     List<ModelValidationResult> result = new List<ModelValidationResult>(); 

     //Need to call the action and check the result here 

     //Create the controller with reflection? 

     //Call the method with reflection? 

     if(false was returned) { 
      result.Add(new ModelValidationResult("", "{0} is invalid")); 
     } 

     return result; 

    } 
} 

それはあなたが混合され、使用

[AjaxValidation ("Validate", "Home", "Examples")] 
public string Value{ get; set; } 

とモデルは(また、クライアント側で使用される)を呼び出しますアクション

public ActionResult Validate(string id) { 

    if (id.Length == 3) { 
     return Json(new { Success = true }); 
    } else { 
     return Json(new { Success = false }); 
    } 

} 

答えて

1

です示すモデル物事を自分では困難にする方法でここにさまざまな概念。

代わりに、検証ロジックをコントローラに取り込むために、検証ロジックを別のサービスに抽出する必要があります。コントローラと属性の両方で問題なく使用できます。 DataAnnotationsなどで構築されたさまざまな方法を使用してこれを行うことができる多くの方法がありますが、少なくともあなたはコードを別のサービスに引き出すことができます。

まず、あなたの検証サービスを作成

public class Validator 
{ 
    public bool Validate(string id) 
    { 
    if (id.Length == 3) { 
     return true; 
    } else { 
     return false; 
    } 
    } 
} 

必要に応じて結果を返すために、既存のコントローラにこれを注入する:

public class ValidationController 
{ 
    private readonly ValidationService _validator; 

    public ActionResult Validate(string id) { 
    var result = _validator.Validate(id); 
    return Json(new { Success = result }); 
    } 
} 

あなたはその後、同様にバリデータを持っているあなたのアクションフィルタを設定する必要があります注射した。 ASP.NET Core Action Filtersを読んで、実行時にServiceFilter属性を使ってサービスを注入する方法をお勧めします。 This answerは、私があなたが探していると思うものを達成する方法を記述しています。

関連する問題