I have just started to work on web applications, and learning to use ASP.Net. I have come across two methods to add script in an HTML page. One is by using script tag, and other one is by using <% ... %>
tag. But, I am unable to figure out, what is the difference between both, and which one should I prefer in which case?
脚本标记用于指定完整脚本(通常是完整的方法/功能)(主要是客户端脚本,但您也可以使用服务器端脚本块),而<% ... %>
用于包括服务器端内联片段。
The tag can be JavaScript or the language in question. The <% %> is functionally equivalent to
<script language="C#|vb" runat="server">
In general, you put the code in code behind (win forms), so the only is for client side script (generally JavaScript). With ASP.NET MVC, the <% %> is for marking up the view and is not really code.
<% %>
用于asp.net编码,<script>标签可以用于任何语言,通过指定您要使用的语言,例如这个用于javascript的<script type="text/javascript">
Script tags are used to add Javascript (or similar) script to the final HTML which is rendered by the browser, and hence allow client-side scripting.
<% ... %>
tags are ASP tags that are processed on the server side, and will not be present in the rendered HTML.
What do you mean by script
tag?
<script language="C#" runat="server">
...
</script>
this is used when you specify that you do not want to place the server code in a separated file, such as myFile.aspx.cs
or in VB myFile.aspx.vb
, this will be the code to run before the page is rendered and will act in compliance with the ASP.NET Page Events Cycle.
The tags <% %>
are used to place Server Code in your page , just like plain old Classic ASP.
Normally we use as Response.Write
using <%= ... %>
but if you use Resources Files, you will end up using <%$ ResourceFile.Variable %>
as well
It's a mean to inject server code into the page
the script tag indicates where client script is going to be executed or if in a function where it is to be organized. The <% .. %> is code that is executed on the webserver and is never seen by the client.
<script>
window.alert("hi") // This will popup a hi message
</script>
<% responce.wrtie("hi") %>
When you load this page you would see a popup and the text hi however in the page source you would see
<script>
window.alert("hi") // This will popup a hi message
</script>
hi
Particularly in case of ASP.net
Code inside script tag is directly placed directly under the class that is generated by the asp.net when the aspx page is requested.
(Every time a request is made to .aspx page , the page is parsed into a .cs file whose path can be found out by using <%=GetType().Assembly.Location%>.And also you have to set the Debug=true in the page directive.)
Code inside <% %> is placed inside a method in the generated class file. For example you can not write Response.Write() directly inside the script tag as it needs to be written inside a method.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.