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

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

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


当前回答

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

其他回答

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

<输入类型=“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"。

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

runat="Server"表示HTML“控件”将回发到服务器。

Web表单不断地使用回发来通知服务器处理页面控制事件。

. net MVC页面不使用回发(表单“submit”除外)。MVC依赖JQUERY在客户端管理页面(因此绕过了向服务器发送大量回发消息的需要)。

所以: .NET Web表单…在页面标记中经常使用“runat”属性。

. net MVC很少在页面标记中使用“runat”属性。

希望这有助于澄清为什么runat是必要的…

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