C# RegisterStartupScript 和 RegisterClientScriptBlock 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/666519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between RegisterStartupScript and RegisterClientScriptBlock?
提问by Xaisoft
Is the only difference between the RegisterStartupScript
and the RegisterClientScriptBlock
is that RegisterStartupScript puts the javascript before the closing </form>
tag of the page and RegisterClientScriptBlock puts it right after the starting <form>
tag of the page?
是的唯一区别RegisterStartupScript
和RegisterClientScriptBlock
被认为的RegisterStartupScript提出的JavaScript结束前</form>
的页面,它开始之后的RegisterClientScriptBlock看跌期权的标签<form>
页的标签?
Also, when would you choose one over the other? I wrote up a quick sample page where I had an issue and I am not sure the exact reason of why it is happening.
另外,你什么时候会选择一个?我写了一个快速示例页面,我遇到了一个问题,但我不确定它发生的确切原因。
Here is the aspx markup:
这是 aspx 标记:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDisplayDate" runat="server"
Text="Label" /><br />
<asp:Button ID="btnPostback" runat="server"
Text="Register Startup Script"
onclick="btnPostback_Click" /><br />
<asp:Button ID="btnPostBack2" runat="server"
Text="Register"
onclick="btnPostBack2_Click" />
</div>
</form>
</body>
</html>
Here is the Code Behind:
这是背后的代码:
protected void Page_Load(object sender, EventArgs e)
{
lblDisplayDate.Text = DateTime.Now.ToString("T");
}
protected void btnPostback_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script language='javascript'>");
sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
sb.Append(@"lbl.style.color='red';");
sb.Append(@"</script>");
if(!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(),"JSScript",
sb.ToString());
}
}
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script language='javascript'>");
sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
sb.Append(@"lbl.style.color='red';");
sb.Append(@"</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock",
sb.ToString());
}
}
The problem is when I click the btnPostBack
button, it does a postback and changes the label to red, but when I click the btnPostBack2
, it does a postback, but the label color does not change to red. Why is this? Is it because the label is not initialized?
问题是当我单击btnPostBack
按钮时,它会进行回发并将标签更改为红色,但是当我单击 时btnPostBack2
,它会进行回发,但标签颜色不会更改为红色。为什么是这样?是不是因为标签没有初始化?
I also read that if you are using an UpdatePanel
, you need to use ScriptManager.RegisterStartupScript
, but if I have a MasterPage
, would I use ScriptManagerProxy
?
我还读到,如果您使用的是UpdatePanel
,则需要使用ScriptManager.RegisterStartupScript
,但是如果我有MasterPage
,我会使用ScriptManagerProxy
吗?
采纳答案by Cerebrus
Here's an old discussion threadwhere I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.
这是一个旧的讨论线程,我在其中列出了主要差异以及您应该使用每种方法的条件。我认为您可能会发现进行讨论很有用。
To explain the differences as relevant to your posted example:
要解释与您发布的示例相关的差异:
a. When you use RegisterStartupScript
, it will render your script afterall the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.
一种。当您使用 时RegisterStartupScript
,它将在页面中的所有元素之后(就在表单的结束标记之前)呈现您的脚本。这使脚本能够调用或引用页面元素,而不会在页面的 DOM 中找不到它们。
Here is the rendered source of the page when you invoke the RegisterStartupScript
method:
这是调用该RegisterStartupScript
方法时页面的呈现源:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<div> <span id="lblDisplayDate">Label</span>
<br />
<input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
<br />
<input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
</div>
<!-- Note this part -->
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
</script>
</form>
<!-- Note this part -->
</body>
</html>
b. When you use RegisterClientScriptBlock
, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.
湾 当您使用 时RegisterClientScriptBlock
,脚本会在 Viewstate 标记之后呈现,但在任何页面元素之前呈现。由于这是一个直接脚本(不是一个可以调用的函数,它会立即被浏览器执行。但浏览器在这个阶段没有在页面的 DOM 中找到标签,因此您应该收到“找不到对象”错误。
Here is the rendered source of the page when you invoke the RegisterClientScriptBlock
method:
这是调用该RegisterClientScriptBlock
方法时页面的呈现源:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
// Error is thrown in the next line because lbl is null.
lbl.style.color = 'green';
Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that functionusing the former method (or add a client side attribute).
因此,总而言之,如果您打算呈现函数定义,您应该调用后一种方法。然后,您可以使用前一种方法(或添加客户端属性)呈现对该函数的调用。
Edit after comments:
评论后编辑:
For instance, the following function would work:
例如,以下函数将起作用:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function ChangeColor() {");
sb.Append("var lbl = document.getElementById('lblDisplayDate');");
sb.Append("lbl.style.color='green';");
sb.Append("}</script>");
//Render the function definition.
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
//Render the function invocation.
string funcCall = "<script language='javascript'>ChangeColor();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
回答by c-sharp user
Here's a simplestexample from ASP.NET Community, this gave me a clear understanding on the concept....
这是来自 ASP.NET 社区的一个最简单的例子,这让我对这个概念有了清晰的理解......
what difference does this make?
这有什么区别?
For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript
method:
举个例子,下面是一种在页面加载到浏览器时将焦点放在页面上的文本框上的RegisterStartupScript
方法——在 Visual Basic 中使用该方法:
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.
这很有效,因为页面上的文本框是在浏览器到达页面底部并访问这一点 JavaScript 时生成并放置在页面上的。
But, if instead it was written like this (using the RegisterClientScriptBlock
method):
但是,如果它是这样写的(使用RegisterClientScriptBlock
方法):
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
Focus will not get to the textbox control and a JavaScript error will be generated on the page
焦点不会到达文本框控件,页面上将生成 JavaScript 错误
The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.
这样做的原因是浏览器会在文本框出现在页面上之前遇到 JavaScript。因此,JavaScript 将无法找到 TextBox1。