为什么我必须指定runat="server"在我所有的ASP。在我有限的ASP知识中,服务器是唯一可用的选项。NET,我得到一个错误,如果我不使用它?

我知道我可以选择在我的HTML标记上使用它,我也知道客户机/服务器范例以及它实际指定的内容。

它是一个多余的标记,可以只是暗示控件是一个ASP。NET控制,还是有一个潜在的原因?


当前回答

微软Msdn文章《被遗忘的控件:HTML服务器控件》以文本框<input type="text">为例解释了runat=" Server "的使用,将其转换为<input type="text" id="Textbox1" runat=" Server ">

Doing this will give you programmatic access to the HTML element on the server before the Web page is created and sent down to the client. The HTML element must contain an id attribute. This attribute serves as an identity for the element and enables you to program to elements by their specific IDs. In addition to this attribute, the HTML element must contain runat="server". This tells the processing server that the tag is processed on the server and is not to be considered a traditional HTML element.

简而言之,要启用对HTML元素的编程访问,请在其中添加runat="server"。

其他回答

并非所有可以包含在页面中的控件都必须在服务器上运行。例如:

<输入类型=“submit”runat=服务器/>

这本质上与:

<asp:Button runat=server />

从第一个按钮中删除runat=server标记,您就有了一个在浏览器中运行的标准HTML按钮。支持和反对在服务器上运行特定控件的理由有很多,而ASP。NET根据所包含的HTML标记“假定”您想要的内容。为<asp:XXX />控件家族“推断”runat=server可能是可能的,但我猜微软会认为这是对标记语法和asp。净引擎。

微软Msdn文章《被遗忘的控件:HTML服务器控件》以文本框<input type="text">为例解释了runat=" Server "的使用,将其转换为<input type="text" id="Textbox1" runat=" Server ">

Doing this will give you programmatic access to the HTML element on the server before the Web page is created and sent down to the client. The HTML element must contain an id attribute. This attribute serves as an identity for the element and enables you to program to elements by their specific IDs. In addition to this attribute, the HTML element must contain runat="server". This tells the processing server that the tag is processed on the server and is not to be considered a traditional HTML element.

简而言之,要启用对HTML元素的编程访问,请在其中添加runat="server"。

任何带有runat=server的标签都被添加为Page中的服务器控件,而两者之间的任何html内容都被处理为LiteralControls,这些LiteralControls也被添加到Page控件集合中。

我通常不喜欢猜,但这次我要猜了……

如果你还记得微软当年(2001年?)的。net营销炒作,那时候甚至还很难说。net是什么。是服务器吗?一个编程平台?一种语言?全新的东西?考虑到广告,它含糊地是你想要的任何东西——它只是解决了你可能遇到的任何问题。

所以,我猜ASP有一个隐藏的宏伟愿景。.NET代码可以在任何地方运行——服务器端或客户端,在与.NET运行时绑定的Internet Explorer副本中。Runat ="server"只是一个残余,因为它的客户端对等物从未进入生产环境。

还记得那些奇怪的广告吗?

相关:来自The Register的文章,介绍了一些。net历史。

我认为微软可以通过让编译器在页面编译之前添加runat属性来解决这种歧义,就像java在泛型中所具有的类型擦除一样,而不是擦除,它可以在看到asp:标签前缀的任何地方写入runat=server,因此开发人员不需要担心它。