Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

asp.net - Understanding the runat server attribute

I'm really new to ASP.NET. I was just checking out a default ASP.NET web application. It comes by default with a few pages (Default.aspx, About.aspx etc).

I noticed that the Site.master file is the file where i create the main layout for my pages. But i also noticed that the head tag has a runat="server" attribute.

I know this tag is used in <asp:XXX> tags, but why in a <head> tag???

Also, when i remove that attribute, then all of the styles are gone from the webpage. So appearently it's doing something. I just don't understand what its exactly doing...

So why is it there, on an HTML tag...??? I don't see any code in there that should be run on the server...

<head runat="server">
    <title>Hallo</title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

    <!-- This part is run on the server. So why does the head tag
         also need a runat=server ?? -->
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You asked why the styles are not applied anymore when removing the runat="server" from the<head> element.

It is simple: by running on the server side, the parser will replace the ~/ from the stylesheet declaration <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> with the root path of the application.

The ~ is illegal in a URL. Thus, if this is not replaced by the parser, the file will not be found thus the stylesheet will not be applied.

Oh, btw, setting the runat="server" attribute on the <head> element will force all its sub-elements to be run on the server, thus why the <link> element is run on the server.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...