ScriptManager.RegisterStartupScript调用的客户端方法未触发

时间:2009-12-17 07:35:05

标签: c# asp.net scriptmanager registerstartupscript

有人可以看下面的代码并告诉我我做错了什么。

for(i=0;i<=Request.Files.Count;i++)
{

int percentComplete = (int)Math.Ceiling((double)(i + 1) / (double)Request.Files.Count * 100);
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count);

ScriptManager.RegisterStartupScript(this, this.GetType(), "progress", @"do_progress("+message+","+percentComplete+");", true);

}

我正在尝试使用循环的每次传递来更新客户端。在客户端(表单标签内)我有一个名为“do_progress”的函数,它有两个参数:message和percent。我的意图是客户端方法随着循环的每次传递而触发,但没有任何反应。

更新

感谢您的帮助。 Ramiz,你的代码在我的情况下不起作用,因为它收集循环中的所有方法(和进度),然后同时将它们发送到客户端。 这不会准确显示进度(每个循环代表上传文件的完成)。在每次唯一完成服务器端循环之后,我需要访问客户端函数do_progress。

此外,页面已加载,单击(上传)按钮时会触发代码。

话虽如此,我仍然遇到问题。通过查看'选择源',我可以通过以下代码确认我得到了我想要的结果:

int percentComplete = (int)Math.Ceiling((double)(i + 1) / (double)Request.Files.Count * 100);

string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count);

ScriptManager.RegisterStartupScript(this, this.GetType(), "progress" + i, @"do_progress('" + message + "','" + percentComplete + "');", true);

但是,我没有看到结果在客户端上实时更新。进度条没有移动,计数器(n个文件中的n个)没有做任何事情。但是,当我查看innerHTML时,值已更新。很奇怪。这几乎就像我需要刷新页面或其他东西,但这不应该是必要的。

我正在使用的客户端功能,位于页面末尾的表单标签中,如下所示:

function do_progress(message,percent)
                    {
                        try {
                            $('progress_status').innerHTML = message;
                            $('progress_bar').attr("style", percent + "px"); 
                        }catch(e){alert(e.message)};
                    }   

3 个答案:

答案 0 :(得分:0)

message string 值,应将其括在单引号中"do_progress('"+message+"',"+percentComplete+");"

percentComplete 包含 integer ,因此不需要将 message 确实。

string methods = string.empty;

for(i=0;i<=Request.Files.Count;i++)
{

int percentComplete = (int)Math.Ceiling((double)(i + 1) / (double)Request.Files.Count * 100);
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count);

methods += "do_progress('"+message+"','"+percentComplete+"');"

}

其次,在这里,我正在递增 string 变量中的所有方法,并在 window.onload 事件中调用它,只需确保<在我们调用 DOM 函数之前,strong> do_progress 已准备就绪。

ScriptManager.RegisterStartupScript(this, this.GetType(), "progress", @"window.onload = function() {"+ methods +"}", true);

但是,此处不需要这样做,请在 window.onload 中进行调用,因为 ScriptManager.RegisterStartupScript 会在 DOM时调用它们准备好了。

我不确定到底是什么问题,但这是我的即时评论。

答案 1 :(得分:0)

尝试使用this.RegisterStartupScript而不是ScriptManager.RegisterStartupScript

答案 2 :(得分:0)

您的客户端do_progress函数似乎在jQuery选择器中出错 - 您当前正在寻找名为progress_statusprogress_bar元素怀疑你打算寻找班级或ID。如果你的选择器不匹配任何东西它不会引起任何类型的错误,它就不会做任何事情。