ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

控制器重定向后,JavaScript无法在视图中执行

2019-12-01 05:33:20  阅读:304  来源: 互联网

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


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

我正在使用以下链接来调用“帐户”控制器的LogOff操作(此代码在单独的控制器中):

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

Account控制器中的LogOff方法如下所示,我在其中传递了一个注销参数,以便在“登录”视图中检测到我来自注销操作:

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

在检查萤火虫时,我注意到javascript

$(document).ready(function () { ... });

在登录页面中使用的代码根本无法执行.

此外,登录页面的URL读取的是“ localhost:##### / Account / LogOff”,而不是我期望的“ localhost:##### / Account / LogOn?logout = True”.

如果我之后尝试提交登录表单,那么我将被发送到网址为“ 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 -->

解决方法:

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

The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.

仅对我而言,“ 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会影响页面上显示的元素.

标签:jquery-mobile,javascript,asp-net-mvc-3
来源: https://codeday.me/bug/20191201/2078703.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有