我已经通读了网络,但还没有找到解决以下问题的方法。我有一个示例页面(_scriptmanager.aspx),其中
ScriptManager
,一个
UpdatePanel
A
MultiView
用两
Views
两个
LinkButtons
两种视图切换。第二个视图包含一些功能,我想为(_scriptmanager.js)加载一个javascript文件。
因为我不知道用户是否会访问视图2,所以我不想为每个请求静态地包含javascript文件。我只想在需要的时候加载它。因此,我需要在异步回发期间包含脚本文件,这正是我使用的方法
ScriptManager.RegisterClientScriptInclude
为。痛苦是:它不起作用。脚本include不会在客户端上执行,因此无法使用其中的javascript函数。更糟的是,我注册的脚本块
ScriptManager.RegisterStartupScript
在这种情况下不会被执行!这都很刺激。有趣的是,include脚本和脚本块确实通过异步回发(fiddler是我的朋友:-)发送到客户机,并且脚本文件也被加载。但后来,javascript似乎有点崩溃了…
有人知道或知道报告的错误吗?
_脚本管理器.aspx
:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="_ScriptManager.aspx.cs" Inherits="Frontend.Web._Tests.ScriptManagerTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scm"></asp:ScriptManager>
<asp:Label runat="server" ID="lbOut">Outside of UpdatePanel</asp:Label>
<div style="border: solid 1px red;">
<asp:UpdatePanel runat="server" ID="up" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:LinkButton runat="server" ID="btnFirst">Show view 1</asp:LinkButton>
<asp:LinkButton runat="server" ID="btnSecond">Show view 2</asp:LinkButton>
</div>
<div>
<asp:MultiView runat="server" ID="mv">
<asp:View runat="server" ID="vw1">First view - static content</asp:View>
<asp:View runat="server" ID="vw2">
Second view - dynamically loaded content (between dashes):
<div>#<span id="divDyn"></span>#</div>
</asp:View>
</asp:MultiView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
_脚本管理器.js
(在这里,我只添加了一些id=divdyn的动态内容到跨度中):
function dynamic() {
alert('dynamic');
$('#divDyn').text('Dynamic!');
}
_脚本管理器.aspx.cs
代码落后:
public partial class ScriptManagerTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnFirst.Click += delegate { mv.SetActiveView(vw1); };
btnSecond.Click += delegate { mv.SetActiveView(vw2); };
if (!IsPostBack)
{
// Test 1: does not work
mv.SetActiveView(vw1);
// Test 2: works, because required script is loaded on initial page request
//mv.SetActiveView(vw2);
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (mv.GetActiveView() == vw2)
{
// Not calling the RegisterClientScriptInclude
// makes the alert work in both cases, but this is
// what it's all about: including script only when
// needed!
ScriptManager.RegisterClientScriptInclude(
Page, Page.GetType(), "include-js",
ResolveClientUrl("~/ScriptManager.js"));
ScriptManager.RegisterStartupScript(
this, GetType(), "call-dynamic",
"alert('hi there'); dynamic();", true);
}
}
}