2011-06-21 23 views
4

私はリモート認証を使用して、my asp.net mvc 3アプリケーション(C#)の登録時にユーザー名の可用性をチェックしています。 - 障害状態 リモート検証成功応答のカスタムメッセージを表示

    1. 表示、エラーメッセージ「利用できません。ユーザー名」:私は2つの条件にメッセージを表示する必要が

      [Remote("IsUserNameAvailable", "User")] 
      public string UserName { get; set; } 
      

      :として私はMVCリモート属性の検証を使用しています

      成功のメッセージ "成功したユーザー名"を表示 - 成功条件

    私のようないかなる問題なく失敗条件のメッセージを表示することができています:

    return Json("Username not available", JsonRequestBehavior.AllowGet); 
    

    しかし、成功の条件のために、私は(ないカスタムメッセージで)対応して真送信する必要があるとして:

    return Json(true, JsonRequestBehavior.AllowGet); 
    

    リモート検証の成功条件にカスタムメッセージを表示するにはどうすればよいですか?

  • 答えて

    0

    (これはJsonにシリアル化される)オブジェクトを返すことができますか?など

    var answer = new { success = true, message = "Username available" }; 
    return Json(answer, JsonRequestBehavior.AllowGet); 
    

    それからビューでこれを解析することができます。

    また、このようにしてもユーザー名が利用できない場合は、ユーザー名をいくつか追加することもできます。

    // pretend they chose "dave" 
    List<string> alternativeNames = new List<string>() { "dave1", "dave2" }; 
    var answer = new { success = false, message = "Username not available", alternatives = alternativeNames }; 
    return Json(answer, JsonRequestBehavior.AllowGet); 
    
    +0

    どのように私は、リモート検証のためにこれを解析していますか?リモート検証はjquery.validate.min.jsにあります。私はどのようにその部分を書き直すのですか? – Prasad

    2

    このリンクを参照してください...それを達成するために here

    一つの方法は、検証アクションからカスタムHTTPレスポンスヘッダを追加することです:クライアント我々の今

    public ActionResult IsUserNameAvailable(string username) 
    { 
    if (IsValid(username)) 
    { 
        // add the id that you want to communicate to the client 
        // in case of validation success as a custom HTTP header 
        Response.AddHeader("X-ID", "123"); 
        return Json(true, JsonRequestBehavior.AllowGet); 
    } 
    
    return Json("The username is invalid", JsonRequestBehavior.AllowGet); 
    } 
    

    明らかにユーザー名の標準フォームと入力フィールドを持つ:

    @model MyViewModel 
    @using (Html.BeginForm()) 
    { 
        @Html.EditorFor(x => x.UserName) 
        @Html.ValidationMessageFor(x => x.UserName) 
        <button type="submit">OK</button> 
    } 
    

    今パズルの最後のピースは、ユーザー名フィールドに、リモート・ルールに完全なハンドラをアタッチすることです:

    $(function() { 
    $('#UserName').rules().remote.complete = function (xhr) { 
        if (xhr.status == 200 && xhr.responseText === 'true') { 
         // validation succeeded => we fetch the id that 
         // was sent from the server 
         var id = xhr.getResponseHeader('X-ID'); 
    
         // and of course we do something useful with this id 
         alert(id); 
        } 
    }; 
    }); 
    
    関連する問題