2

ajaxで検証したい簡単なログインフォームを作成しました。

MVCによって生成されたサーバー側の検証エラーを表示するための最も適切な方法は何ですか?エラーをJSON結果に変換し、エラーメッセージを取り除くことは適切ですか?そうでない場合は、どうなりますか?

現在、私が持っているのは正しく投稿していますが、フォーム全体が戻ってきます。目標は、ポストバック/更新なしでサーバー側のエラーをフォームに表示することです。事前に感謝します...ここに私のコードがあります:

メインビュー-Login.vbhtml

@ModelType UHCO_MVC_Agency.LoginModel

<div class="error-container">@Html.ValidationSummary(True)</div>
<div class="row-fluid">
    <div class="span12">
        <div id="login-form" class="span6">
            @Using Html.BeginForm()
               @<fieldset>
                  <legend>Log in to your account now</legend>
                  <div class="row-fluid">
                     <div class="span12">
                        @Html.LabelFor(Function(m) m.UserName)
                        @Html.TextBoxFor(Function(m) m.UserName, New With {.class = "span12", .placeholder = "Username"})
                        @Html.ValidationMessageFor(Function(m) m.UserName)
                     </div>
                  </div>
                  <div class="row-fluid">
                     <div class="span12">
                        <label for="Password">Your password</label>
                        @Html.PasswordFor(Function(m) m.Password, New With {.class = "span12", .placeholder = "Password", .type = "password"})
                        @Html.ValidationMessageFor(Function(m) m.Password)
                     </div>
                  </div>
                  <div class="row-fluid">
                     <div class="span12">
                        <label for="RememberMe" class="checkbox clearfix">
                           @Html.CheckBoxFor(Function(m) m.RememberMe)
                           Remember me next time I visit
                        </label>
                     </div>
                  </div>
                  <button type="submit" class="btn btn-primary input-small" value="submit">Log in</button>
               </fieldset>
            End Using
         </div>
      </div>
</div>

コントローラー-AccountController.vb

<HttpPost()> _
Public Function Login(ByVal model As LoginModel, ByVal Username As String, ByVal Password As String, ByVal returnUrl As String) As ActionResult
   Dim res As New LoginResponse()
   Try
      'login here
   If Not String.IsNullOrEmpty(returnUrl) AndAlso Url.IsLocalUrl(returnUrl) Then
      res.Status = "Success"
      Return RedirectToAction("Welcome", "Account")
   End If
   Catch ex As Exception
      If Not HttpContext.Request.IsAjaxRequest() Then
         ModelState.AddModelError("", ExceptionWrapper.Wrap(ex).ExceptionMessage())
         Return View("Login", model)
      Else
         res.Status = "Failed"
         res.Errors.Add(ExceptionWrapper.Wrap(ex).ExceptionMessage())
         Return Json(res)
      End If
   End Try
   ' If we got this far, something failed, redisplay form
   Return View(model)
End Function

Application.js

$("#login-form form").live().submit(function (e) {
  e.preventDefault();
  alert("ok");
});
4

2 に答える 2

1

これは、ソリューションのC#バージョンです。対応するVB.NETバージョンに簡単に変換できるはずだと思います

JSONを使用することは、これを行うための絶対に良い方法です。

初めにすること。アクションメソッドを変更してPOST、Ajaxリクエストのリクエストを処理し、JSONレスポンスを返します。

エラー応答を保持するために、次のようなクラスを作成します

public class LoginResponse
{
  public string Status { set;get;}
  public List<string> Errors { set;get;}

  public LoginResponse()
  {
    Errors=new List<string>();   
  }       
}

そして私たちのPOST行動方法では

[HttpPost]
public ActionResult Login(LoginModel model)
{
  if(Request.Ajax)
  {
       var res=new LoginResponse();
     //Do your Validations, If everything is fine send Success JSON
        res.Status="Success";

     //else, Lets return a JSON with errors
        res.Status="Failed";
        res.Errors.Add("Email does not exist in Earth and Mars");
        res.Errors.Add("Password contain the word black magic");

     return Json (res);
  }
  else
  {
     //Do the normal Processing for Non Ajax requests here
  }
}

したがって、クライアントに返したいエラーがある場合は、この形式でJSONを送信します

{
    "Status": "Failed",
    "Errors": [  "Email does not exist",  "Passoword is worse"  ]
}

そして、すべてがうまくいけば、このようなJSONを送信します

{
    "Status": "Success"
}

ここで、Ajaxフォームを削除し、純粋なjQueryでNormalフォームタグを使用します。

@ModelType UHCO_MVC_Agency.LoginModel
@using(Html.BeginForm())
{
  //Here your for elements

  <input type="submit" id="btnSubmit"/>
}
<script type="text/javascript">

$(function(){
   $("#btnSubmit").click(function (e) {
      e.preventDefault();
     $.post("@Url.Action("Login","User")", $("form").serialize(), function (r) {
       if(r.Status=="Success")
       {
         //Login is success . do whatever you want.
       }
       else
       {
         //Lets get the Errors from our JSON
         $.each(r.Errors,function(index,item){
             //Lets show the error
              $("#errorSummary").append(item);
         }  
       }
     });

});    
</script>

編集:このようにjsコードを変更して、何が起こるかを確認してください

$("#login-form form").live('submit', function(e){
   e.preventDefault();
  //the code

});
于 2012-08-31T20:06:20.043 に答える
0

私は決してVBの男ではありませんが、あなたがする必要があるのはこれだと思います:

1)コントローラーで、AJAX経由で到着したかどうかを確認する必要があります。これを示すために、データと一緒に追加の情報を送信するか、SERVER['HTTP_X_REQUESTED_WITH']最も一般的なライブラリによって送信されるXMLHTTPRequestを使用して確認することができます。

2)ページが実際にAJAXを介して要求された場合は、出力をパッケージ化するときに別のプロセスを実行できます。JSONのみを返し、クライアント側でDOMを操作して解析します。

于 2012-08-31T20:07:23.133 に答える