不返回任何视图的控制器方法

时间:2012-03-23 14:37:50

标签: jquery asp.net asp.net-mvc-3 jquery-ui razor

如何更改此方法以检查登录名和密码,并且不刷新日志表单所在的整个页面(日志表单位于jQuery对话框中)。此方法不应将我重定向到/ Home / Index或刷新整个页面。应该登录我,然后jQuery脚本应该关闭对话窗口。

的AccountController:

[HttpPost]
    public ActionResult LogOnDialogForm(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View("LogOn");
    }

jQuery脚本从视图(我有登录按钮打开对话框):

<script>
$(function () {
    $("#dialog:ui-dialog").dialog("destroy");

    var name = $("#name"),
        password = $("#password"),
        allFields = $([]).add(name).add(password),
        tips = $(".validateTips");

    function updateTips(t) {
        tips
            .text(t)
            .addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 500);
        }, 500);
    }

    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " +
                min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    $("#dialog-form").dialog({
        autoOpen: false,
        height: 380,
        width: 350,
        modal: true,
        buttons: {
            "Login": function () {
                var form = $('form', this);
                $(form).submit();
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });

    $("#login")
        .button()
        .click(function () {
            $("#dialog-form").dialog("open");
        });
});
</script>

查看包含表单正文的内容:

    @model BlogNet.Models.LogOnModel

<p>
    @Html.ActionLink("Register", "Register") if you don't have an account.
</p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")

@using (Html.BeginForm("LogOnDialogForm", "Account", FormMethod.Post, new { @class = "dialogForm"}))
{
    <div>
        <fieldset>
            <div class="editor-label">
                @Html.LabelFor(m => m.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </div>

            <div class="editor-label">
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
            </div>
        </fieldset>
    </div>
}

2 个答案:

答案 0 :(得分:1)

您需要AJAXify您的登录表单。现在它是一个标准的HTML <form>,它在提交POST时将输入字段发送到服务器并刷新整个页面。

所以:

"Login": function () {
    var dialog = this;
    var form = $('form', dialog);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        success: function(result) {
            if (result.success) {
                // authentication was successful 
                // Here you can close the dialog, redirect, refresh
                // some part of the DOM, whatever you want
                $(dialog).dialog("close");
            } else {
                // an error occurred => we refresh the dialog:
                $('#dialog-form').html(result);
            }
        }
    });
}

并且您还应该修改控制器操作,以便在成功进行身份验证时,它只返回JSON而不是重定向:

if (Membership.ValidateUser(model.UserName, model.Password))
{
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
    {
        return Json(new { success = true, returnUrl = returnUrl });
    }
    else
    {
        return Json(new { success = true, returnUrl = Url.Action("Index", "Home") });
    }
}

答案 1 :(得分:0)

尝试更改代码的Login部分:

"Login": function () {
    var form = $("form", this);
    $.post(form.attr("action"), form.serialize(), function(data) {            
        if ($(data).find(".validation-summary").length > 0)
        {
            $("#dialog-form").html(data);
        }
        else { $(this).dialog("close"); }
    });
},