mvc3客户端验证没有解雇

时间:2012-09-07 02:37:05

标签: jquery asp.net-mvc-3 validation client-side

(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>

3 个答案:

答案 0 :(得分: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");
    }

答案 1 :(得分:1)

通过在提交功能上手动发送表单,您不允许验证器启动。因此,您绕过验证器及其所有不显眼的细节。

如果要进行ajax回发,请改用Ajax.BeginForm帮助程序。它将为您提供在加载时从表单中执行阻止所需的挂钩,并且还具有onsuccess回调以执行重定向。

如果没有启用javascript,那么它将恢复为普通形式,并且将调用action方法,您的控制器可以处理并正确返回。

示例:

<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
     *@
}

的Si

答案 2 :(得分: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”。