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

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

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


当前回答

它的存在是因为ASP . net中的所有控件都继承自System.Web.UI.Control,后者具有“runat”属性。

在System.Web.UI类中。HTMLControl,这个属性不是必需的,但是在System.Web.UI.WebControl类中,这个属性是必需的。

编辑: 让我说得更具体一点。因为asp.net基本上是HTML的抽象,所以编译器需要某种指令,以便它知道特定的标签需要在服务器端运行。如果该属性不存在,则不知道首先在服务器上处理它。如果它不存在,它会假设它是常规标记并将其传递给客户端。

其他回答

在向ASP提交数据时。在服务器应用程序中,Runat = " server "所提到的控件将表示为Dot NET对象。您可以手动在HTML控件中键入代码,或者通过在设计视图中单击右键使用Run As Server选项。 ASP。一旦你将它从工具箱中拖出,NET控件将自动获得此属性,而通常HTML控件不会。

我只是通过反复试验得出了这个结论: 需要Runat ="server"在服务器端运行时访问元素。 删除它们,重新编译,看看会发生什么。

微软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"。

非常多余的属性,考虑到“asp”标记显然是一个asp元素,应该足以将其标识为服务器端可访问元素。

然而,在其他地方,它用来提升普通标记以用于代码背后。

HTML元素在ASP。默认情况下,NET文件被视为文本。要使这些元素可编程,可以在HTML元素中添加runat="server"属性。此属性指示应将元素视为服务器控件。