How to turn Html.BeginForm into Ajax.BeginForm

只愿长相守 提交于 2021-02-19 03:30:40

问题


The following works, but how do I convert this to an 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:


Change your form to this:

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

Make sure your Login action returns the redirect URL, in case of a successful login, and add this script to your View:

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


来源:https://stackoverflow.com/questions/20551571/how-to-turn-html-beginform-into-ajax-beginform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!