操作调用后重定向到jQuery对话框

操作调用后重定向到jQuery对话框,jquery,asp.net-mvc,asp.net-mvc-4,Jquery,Asp.net Mvc,Asp.net Mvc 4,我有一个asp.net MVC网站(Visual Studio 2012,C#),用户可以登录。当他们单击“登录”链接时,会打开一个jQuery对话框,其中呈现部分登录视图。我可以让对话框发布到正确的操作和控制器,但如果用户名/密码组合无效,我需要帮助重定向回对话框屏幕。在继续之前,我已经在Submit按钮上进行了错误检查,以检查这两个按钮中是否存在值,但需要其他部分的帮助 我会尽力解释网站的布局: \u标题部分视图 <header id="header" class="style2"&g

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

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

\u标题部分视图

<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>
<div id="login_panel" style="display: none"></div>
@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>
\u登录视图

<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>
<div id="login_panel" style="display: none"></div>
@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>
以及家庭控制器

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);
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
    // omitted for brevity
    if (user != null)
    {
        Session["LoggedIn"] = true;
        return Json(new { url = Url.Action("Index", "ClientStats") });
    }
}
如您所见,我可以让对话框正确呈现
\u Login
部分视图,它将发布到主控制器上的
Login
操作。我只是不知道如何从操作中重新打开对话框。现在的情况是,网站重定向到主页上的部分视图,而不是对话框中的部分视图


非常感谢您的帮助。

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

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

    \u登录视图

    @* omitted for brevity *@
    @using (Ajax.BeginForm("Login", "Home", new AjaxOptions() { OnComplete = "complete" }))
    {
    
    }
    
    <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>
    
    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);
    }
    
    [HttpPost]
    public ActionResult Login(LoginViewModel model)
    {
        // omitted for brevity
        if (user != null)
        {
            Session["LoggedIn"] = true;
            return Json(new { url = Url.Action("Index", "ClientStats") });
        }
    }
    
    标题部分视图

    @* omitted for brevity *@
    @using (Ajax.BeginForm("Login", "Home", new AjaxOptions() { OnComplete = "complete" }))
    {
    
    }
    
    <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>
    
    
    var jq=jQuery.noConflict(true);
    jq(文档).ready(函数($){
    //为简洁起见省略
    });
    功能完成(响应){
    试一试{
    var data=JSON.parse(response.responseText);
    如果(数据['url'])
    $(location.attr('href',data['url']);
    }
    捕获(e){
    $('login#u panel').html(response.responseText);
    //这是对动态内容重新应用jQuery验证
    $.validator.unobtrusive.parse(“#login_panel”);
    }
    }
    
    您可以尝试使用类似我这里的答案的ajax调用。此外,live已被弃用,因此您应该将.live('click')…更改为.on('click'