如何将Html.BeginForm转换为Ajax.BeginForm

时间:2013-12-12 18:40:13

标签: ajax asp.net-mvc url-redirection

以下有效,但如何将其转换为Ajax Call?

<section id="loginWindow">
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Log in Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.UserName)
            @Html.TextBoxFor(m => m.UserName)
            @Html.ValidationMessageFor(m => m.UserName)
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)
        </li>
        <li>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
        </li>
    </ol>
    <input type="submit" value="Log in" />
</fieldset>

}
</section>

1 个答案:

答案 0 :(得分:5)

将表单更改为:

@using (Ajax.BeginForm("Login", "Account", new AjaxOptions { OnSuccess = "onSuccess" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Log in Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </li>
            <li>
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
            </li>
        </ol>
        <input type="submit" value="Log in" />
    </fieldset>
}

如果登录成功,请确保您的登录操作返回重定向网址,并将此脚本添加到您的视图中:

<script type="text/javascript">
    function onSuccess(result) {
        if(result.url) {
            window.location.href = result.url;
        }
    }
</script>