控制器重定向后,Javascript不会在视图中执行

时间:2012-06-22 19:34:11

标签: javascript asp.net-mvc-3 jquery-mobile

我遇到了一个问题,即在注销后,我会重定向到我网站的登录页面。但是,除非我刷新,否则登录页面的javascript根本不会执行。

我正在使用以下链接调用Account控制器的LogOff操作(此代码位于单独的控制器中):

@Html.ActionLink("Logout", "LogOff", "Account", null, new { data_icon = "gear", @class = "ui-btn-right" })

Account控制器中的LogOff方法如下所示,我在其中传递一个logout参数,以便在Login视图中检测我从注销操作中来到这里:

public ActionResult LogOff()
{
    return Redirect(Url.Action("LogOn", "Account", new RouteValueDictionary(new { logout = true })));
}

签入firebug,我注意到了javascript

$(document).ready(function () { ... });
我的登录页面中使用的

根本不执行。

此外,登录页面的url读取“localhost:##### / Account / LogOff”而不是“localhost:##### / Account / LogOn?logout = True”,这是我预期的。< / p>

如果我之后尝试提交登录表单,那么我会被发送到一个空白页面,其中包含网址“http:// localhost:##### /?logout = True”

所以我想知道我做错了什么阻止了网页加载javascript,以及我如何解决这个问题。

谢谢!

更新 这是我的LogOn控制器方法:

public ActionResult LogOn()
{
    List<SelectListItem> cpList = new List<SelectListItem>();

    // Retrieve the list of central points from web.config
    NameValueCollection centralPoints = (NameValueCollection)ConfigurationManager.GetSection("CentralPointDictionary");

    foreach (string cp in centralPoints)
        cpList.Add(new SelectListItem { Text = cp as string, Value = centralPoints[cp] as string });

    // Check for a cookie containing a previously used central point
    string selectedCP = string.Empty;
    if (ControllerContext.HttpContext.Request.Cookies["LastCentralPoint"] != null)
        selectedCP = ControllerContext.HttpContext.Request.Cookies["LastCentralPoint"].Value;
    else if (cpList.Count > 0)
        selectedCP = cpList[0].Text;
    LogOnModel loginModel = new LogOnModel { CentralPointsList = new SelectList(cpList, "Value", "Text", selectedCP) };
    return View(loginModel);
}

我的观点的主体:

<div data-role="page" id="page">
    <div data-role="header" data-position="inline">
        <div id="languageContainer" data-role="fieldcontain">
        <select id="languageSelect" data-mini="true" data-theme="b" data-overlay-theme="d" data-native-menu="false" data-inline="true">
            <option value="English">English</option>
            <option value="Français">Français</option>
        </select>
        </div>
    </div><!-- /header -->

    <div data-role="content" id="contentFrame" class="frame">
        <div id="controlFrame">
            @using (Html.BeginForm())
            {
            <div id="centralPoint" class="frame">
                    @Html.DropDownListFor(model => model.CentralPointAddress, Model.CentralPointsList, new { id = "centralPointSelect", name = "centralPoint", data_mini = "true", data_inline = "true", data_native_menu = "false" })
            </div>
                <div id="errorMsg">@Html.ValidationSummary()</div>
            <div id="credentialsFrame" class="frame">
                @Html.TextBoxFor(m => m.UserName, new { id = "userField", type = "text", name = "Username" })
                @Html.PasswordFor(m => m.Password, new { id = "passField", type = "password", name = "Password" }) 
            </div>
            <input id="loginBtn" type="submit" value="Login" />
            <div id="rememberMe" class="frame">
                        @Html.CheckBoxFor(m => m.RememberMe, new { @class = "custom", data_mini = "true" })
                        @Html.LabelFor(m => m.RememberMe)
            </div>
            <div id="forgotPassFrame">
                <input id="forgotPass" type="button" data-mini="true" value="Forgot password?" />
            </div>
            @Html.HiddenFor(m => m.Encrypted, new { id = "encrypted", value = "false" })
            }
        </div>
        @using (Html.BeginForm("SuccessfulLogin", "Account", FormMethod.Get, new { id = "successForm" }))
        {
            <input id="returnUrl" name="returnUrl" type="hidden" />
        }
    </div><!-- /content -->
 </div><!-- /page -->

2 个答案:

答案 0 :(得分:3)

确实,问题与jQuery Mobile有关。从JQM文档: http://jquerymobile.com/test/docs/api/events.html

  

你在jQuery中学到的第一件事就是在里面调用代码   $(document).ready()函数,所以一切都会尽快执行   DOM已加载。但是,在jQuery Mobile中,Ajax用于加载   导航时每个页面的内容都放入DOM中,并准备好DOM   处理程序仅对第一页执行。每当执行代码时   加载并创建新页面,您可以绑定到pageinit事件。   此事件在本页底部详细说明。

仅限我,“pageinit”无法使用,但“pagechange”可以解决问题。

所以我最后做的是:从$(document).ready()中提取原始代码并将其插入到单独的函数中。它现在看起来像这样:

$(document).ready(DocumentReady);

$(document).bind("pagechange", function () {
    // check if we just logged out to ensure we don't call DocumentReady() 
    // twice in succession
    if (window.location.href.indexOf("LogOff") > -1) {
        DocumentReady();
    }
});

function DocumentReady() {
    // some initialization code
});

然而...

这解决了我的javscript没有执行的第一个问题,但是我的UI没有显示javascript所做的更改。

正如JQM文档所述,整个应用程序都在一个文档中工作。因此,我的LogOff控制器方法(重定向到LogOn)导致将新的登录页面注入(或附加)到现有页面中。然后当我的javascript代码访问带有$("#userField")的文本输入字段时,它正在从应用程序最开始加载的页面访问该字段,不是登出后显示的字段!

我后来想到的是,通过为window.location赋值来更改页面位置会导致完全刷新。因此,当注销时,我可以这样做,而不是调用控制器方法:

$("#logoutBtn").click(function () {
    window.location = $.mobile.path.parseUrl(window.location.href).domain + "/Account/LogOn";
});

由于这会导致页面完全刷新,因此触发了$(document).ready()事件,这意味着我之前所说的关于绑定到“pagechange”或“pageinit”的内容不再是必需的,尽管仍然非常好了解何时使用jQuery mobile。刷新还会加载一个全新的DOM,因此我可以确定我的javascript会影响页面上显示的元素。

答案 1 :(得分:0)

使用RedirectToAction()代替redirect()