0

(2012 年 9 月 14 日更新)

これは私のコントローラーです:

<HttpPost()> _
Public Function Login(ByVal viewmodel As LoginViewModel) As ActionResult
    Dim result As New LoginResponse()
    Try
        Dim objUserCredentialsType As UserCredentialsType = UserProfileType.Login(viewmodel.UserName, viewmodel.Password, 0, CStr(AppSettings("softwareLicense")))
        'store user credentials in session
        HttpContext.Session.Add("_CurrentUserCredentials", objUserCredentialsType)
        FormsAuthentication.SetAuthCookie(viewmodel.UserName, viewmodel.RememberMe)
        result.Status = "Success"
        result.ReturnUrl = "~/Account/Welcome"
        Return Json(result)
    Catch ex As Exception
        result.Status = "Failed"
        result.Errors.Add(ExceptionWrapper.Wrap(ex).ExceptionMessage())
        Return Json(result)
    End Try
End Function

Public Class LoginResponse
    Public Property Status() As String
        Get
            Return m_Status
        End Get
        Set(value As String)
            m_Status = Value
        End Set
    End Property
    Private m_Status As String
    Public Property Errors() As List(Of String)
        Get
            Return m_Errors
        End Get
        Set(value As List(Of String))
            m_Errors = Value
        End Set
    End Property
    Private m_Errors As List(Of String)
    Public Property ReturnUrl() As String
        Get
            Return m_ReturnUrl
        End Get
        Set(value As String)
            m_ReturnUrl = value
        End Set
    End Property
    Private m_ReturnUrl As String
    Public Sub New()
        Errors = New List(Of String)()
    End Sub
End Class

これは私の見解です:

<section id="login">
    <div id="login-form-container" class="span6">
        @Using (Ajax.BeginForm("Login", "Account", Nothing, New AjaxOptions With {.HttpMethod = "post", .OnBegin = "LoginFormAjaxValidate"}, New With {.id = "login-form"}))
            @<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 id="login-submit" type="submit" class="btn btn-primary input-small" value="submit">Log in</button>
            </fieldset>
        End Using                                  
    </div>
</section>

これは、ビューの下部にあるスクリプトです。

<script type="text/javascript">
function LoginFormAjaxValidate() {
    $("#login-form").serialize(), function (r) {
        if (r.Status == "Success") {
            top.location.href = "@Url.Content("~/Account/Welcome")";
        }
        else {
            //Lets get the Errors from our JSON
            $.each(r.Errors, function (index, item) {
                alert(r.item);
            });
        }
    }
}
</script>
4

3 に答える 3

2

私は VB を使用しませんが、これが私のビュー モデルと ActionMethod が C# でどのように見えるかです。

次の JavaScript ファイルが正しく含まれていることを確認してください

jquery.unobtrusive-ajax jquery.validate.unobtrusive jquery.validate

ビューモデルの注釈も確認してください。レンダリングされた html を表示し、データ検証属性がレンダリングされていることを確認します。

EX 出力は次のようになります。

<input data-val="true" data-val-email="Invalid E-Mail Address" data-val-required="E-Mail Address is required" id="UserName" name="UserName" type="email" value="" />&nbsp;<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true">

残りの Ajax オプションはどこにありますか? 私が見るのはコールバックだけですか??

 @using (Ajax.BeginForm("SignIn", "Account", null, new AjaxOptions
                                                      {
                                                          HttpMethod = "post",
                                                          UpdateTargetId = "ajax-sign-in",
                                                          InsertionMode = InsertionMode.Replace,
                                                          OnSuccess = "Success"
                                                      }, new {@autocomplete = "on"}))
{
 YOUR FORM HTML...... HERE
}



public class AccountSignInViewModel
{
    [Display(Name = "E-Mail Address")]
    [Required(ErrorMessage = "E-Mail Address is required")]
    [EmailAddress(ErrorMessage = "Invalid E-Mail Address")]
    public string UserName { get; set; }
    [Required(ErrorMessage = "Please enter a password")]
    [Display(Name = "Password")]
    public string Password { get; set; }
    [Display(Name = "Remember My Login?")]
    public bool RemeberLogin { get; set; }
}

 [HttpPost]
    public ActionResult SignIn(AccountSignInViewModel accountSignInViewModel)
    {
        if (ModelState.IsValid)
        {
            // DO SOME AUTHENTICATION STUFFS
        }
        return PartialView("_LocalSignIn");
    }
于 2012-09-12T04:05:22.813 に答える
1

送信機能でフォームを手動で送信することにより、バリデーターが作動することを許可しません。したがって、バリデーターとその目立たない機能をすべてバイパスします。

ajax ポストバックを実行する場合は、代わりに Ajax.BeginForm ヘルパーを使用してください。ロード中にフォームからブロックを実行するために必要なフックを提供し、リダイレクトを実行するための onsuccess コールバックも提供します。

JavaScript が有効になっていない場合は、通常の形式に戻り、アクション メソッドが呼び出され、コントローラーがそれを処理して適切に戻ることができます。

例:

<script type="text/javascript">
    function formSuccess(result, status, xhr) {
        // result has the response object
    }

    function formFailed(xhr, status, result) {
        // params are flipped in the error handler, not sure why
    }

    function formBegin(object, xhr) {
        // return false in here if you don't want to submit the form
        return true;
    }
</script>
@using(Ajax.BeginForm("Action", "Controller", new {id = 1 /* route values */ },new AjaxOptions{ OnBegin = "formBegin", OnSuccess = "formSuccess", OnFailure = "formFailure"}, new { @class="form"/* html attributes */ } ))
{
    @*
        put your form bits in here
     *@
}

于 2012-09-10T12:02:01.643 に答える
1

これを追加してみてください:

function ajaxValidate() {
   return $('my-login-form').validate().form();
}

フォーム宣言を次のように変更します。

@Using (Ajax.BeginForm("Login", "Account", Nothing,
    New AjaxOptions With {.HttpMethod = "post",
    .UpdateTargetId = "login-form",
    .OnBegin="ajaxValidate",
    .OnSuccess = "LoginFormSuccess"},
    New With { .id = "my-login-form"}))

また、勇気を出すために、div id="login-form" の名前を id="login-form-container" に変更します。その div の名前を変更する場合は、cs および js コードで「my-login-form」を「login-form」に更新するだけです。

于 2012-09-13T13:46:05.197 に答える