在Action调用后重定向到jQuery Dialog

时间:2013-10-01 20:14:33

标签: jquery asp.net-mvc asp.net-mvc-4

我有一个用户可以登录的asp.net MVC网站(Visual Studio 2012,C#)。当他们单击“登录”链接时,它会打开一个jQuery对话框,该对话框呈现部分登录视图。我可以让对话框发布到正确的操作和控制器,但如果用户名/密码组合无效,我需要帮助重定向回对话框屏幕。我已经对“提交”按钮进行了错误检查,以检查在继续操作之前是否存在值,但需要有关其他部分的帮助。

我会尽力解释网站的布局:

_HeaderPartial View

<header id="header" class="style2">
    <link href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>

    <script type="text/javascript">
        var jq = jQuery.noConflict(true);
        jq(document).ready(function ($) {

            $("#ViewLogin").live("click", function (e) {
                var url = $(this).attr('href');
                $("#login_panel").dialog({
                    title: 'Client Login',
                    closeOnEscape: true,
                    autoOpen: false,
                    resizable: false,
                    height: 350,
                    width: 400,
                    show: { effect: 'drop', direction: "up" },
                    modal: true,
                    draggable: true,
                    open: function (event, ui) {
                        $(this).load(url);

                    },
                    close: function (event, ui) {
                        $(this).dialog('destroy');
                    }
                });

                $("#login_panel").dialog('open');
                return false;
            });
        });
    </script>
    <div class="container">

        <!-- logo -->
        <h1 id="logo"><a href="@Url.Action("Index", "Home")">
            <img src="~/images/small_logo.png" alt="Logo"></a></h1>

        <ul class="topnav navRight">
            <li>&nbsp;</li>

            @if (Session["LoggedIn"] == null || Convert.ToBoolean(Session["LoggedIn"])==false)
            {
                <li><a href="@Url.Action("ViewLogin", "Home")" id="ViewLogin">LOGIN</a></li>
            }
            else
            {
                <li><a href="@Url.Action("LogOut", "Home")">LOGOUT</a></li>
            }
        </ul>

    <other generic html markup omitted>

正如您所看到的,当单击“Login”链接时,jQuery会打开一个对话框,这是一个名为“login_panel”的简单div:

_Layout View

<div id="login_panel" style="display: none"></div>

_Login View

@model MyApp.LoginViewModel
@{
    Layout = null;
}
<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>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

<div id="login_panel">
    <div class="inner-container login-panel">
        <h4>SIGN IN TO ACCESS YOUR ACCOUNT</h4>
        @using (Html.BeginForm("Login", "Home", FormMethod.Post))
        {
            <div class="validation-text">
                <h5>@Html.ValidationSummary()</h5>
            </div>
            <div>
                @Html.LabelFor(x => x.Username)
                @Html.TextBoxFor(x => x.Username, new { placeholder = "Username..." })
            </div>
            <div>
                @Html.LabelFor(x => x.Password)
                @Html.PasswordFor(x => x.Password, new { placeholder = "Password..." })
            </div>
            <br />
            <button class="btn btn-danger" type="submit">LOG IN</button>
            <div class="links"><a href="#" onclick="ppOpen('#forgot_panel', '350');">FORGOT YOUR USERNAME or PASSWORD?</a></div>
        }
    </div>
</div>

LoginViewModel

public class LoginViewModel
{
    [Required(ErrorMessage = "Username is required.")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Password is required.")]
    public string Password { get; set; }
}

HomeController

public ActionResult ViewLogin()
{
    return View("_Login");
}

public ActionResult LogOut()
{
    Session["LoggedIn"] = false;
    return RedirectToAction("Index", "Home");
}

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        using (ProPhysiqueContext db = new ProPhysiqueContext())
        {
            var user = db.Users
                            .Where(u => u.EmailAddress == model.Username &&
                                    u.WebPassword == model.Password).FirstOrDefault();

            if (user != null)
            {
                Session["LoggedIn"] = true;
                return RedirectToAction("Index", "ClientStats");
            }
        }
    }

    ModelState.AddModelError("", "Invalid Username or Password.");

    return PartialView("_Login", model);
}

正如您所看到的,我可以让对话框正确呈现_Login部分视图,它将发布到Home控制器上的Login操作。我无法弄清楚如何从Action中重新打开对话框。现在的方式是,网站重定向到主页上的_Login部分视图,而不是对话框。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如何使用Ajax表单,这样您就不必费力地将视图返回到它所处的状态,即打开对话框。要做到这一点,你需要改变一些事情:

  1. 将您的Html.BeginForm更改为Ajax.BeginForm并将OnComplete属性设置为将被调用的javascript函数,接受响应的单个参数。
  2. 更改您的操作方法,以返回包含重定向网址的JsonResult,而不是RedirectToAction结果。
  3. 在您的javascript函数中,根据回复,您将使用响应替换登录表单的内容或重定向到URL。
  4. 以下是使用您的代码的相关更改。

    _Login View

    @* omitted for brevity *@
    @using (Ajax.BeginForm("Login", "Home", new AjaxOptions() { OnComplete = "complete" }))
    {
    
    }
    

    <强>的HomeController

    [HttpPost]
    public ActionResult Login(LoginViewModel model)
    {
        // omitted for brevity
        if (user != null)
        {
            Session["LoggedIn"] = true;
            return Json(new { url = Url.Action("Index", "ClientStats") });
        }
    }
    

    HeaderPartial View

    <script type="text/javascript">
        var jq = jQuery.noConflict(true);
        jq(document).ready(function ($) {
            // omitted for brevity
        });
    
        function complete(response) {
            try {
                var data = JSON.parse(response.responseText);
                if (data['url'])
                    $(location).attr('href', data['url']);
            }
            catch (e) {
                $('#login_panel').html(response.responseText);
                // this is to reapply jQuery validation to dynamic content
                $.validator.unobtrusive.parse('#login_panel');
            }
        }
    </script>