RegisterStartupScript와 RegisterClientScriptBlock의 차이점은 무엇입니까?
사이의 유일한 차이 RegisterStartupScript
와는 RegisterClientScriptBlock
RegisterStartupScript 닫는 전에 자바 스크립트를두고 있다는 것입니다 </form>
그것은 바로 시작 후 페이지와 RegisterClientScriptBlock 둔다의 태그 <form>
페이지 태그?
또한 언제 다른 것을 선택할 것입니까? 문제가 발생한 빠른 샘플 페이지를 작성했는데 왜 정확한지 잘 모르겠습니다.
다음은 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>
코드는 다음과 같습니다.
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());
}
}
문제는 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
?
Here's an old discussion thread where 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 after all 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.
Here is the rendered source of the page when you invoke the RegisterStartupScript
method:
<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.
Here is the rendered source of the page when you invoke the RegisterClientScriptBlock
method:
<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 function using 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);
}
}
Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....
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:
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.
But, if instead it was written like this (using the RegisterClientScriptBlock
method):
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
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.
'Programming' 카테고리의 다른 글
순수 JavaScript Graphviz 상당 (0) | 2020.06.24 |
---|---|
string_view는 무엇입니까? (0) | 2020.06.24 |
C ++ 초기 할당이 C보다 훨씬 큰 이유는 무엇입니까? (0) | 2020.06.24 |
“FOUNDATION_EXPORT”대“extern” (0) | 2020.06.24 |
Unix 타임 스탬프 '120314170138Z'에서 'Z'는 무엇을 의미합니까? (0) | 2020.06.24 |