Question

When don't you need to use runat="server" in ASP.NET?

EDIT: Thanks for all the answers, but I was really thinking of runat="server" inside an <asp: tag.

Was it helpful?

Solution

Use the runat=server attribute when you're using ASP.NET controls, and/or you require programmatic access to those controls in your code-behind.

HTML controls don't require this attribute. It's useful if you have any HTML element like <span> <div>, or <table> when you want the ability to access them in code-behind.

<asp:Label runat="server" id="foo" />
<div runat="server" id="bar />
...
foo.Text = "Hello Label";
foo.Attributes["class"] = "baz";

OTHER TIPS

You need to use runat="server" on any control that you want to be parsed as a server control.

Any element with runat="server" will be parsed into a server control in the Page herarchy. Anything else will be handled as plain text, and put in LiteralControl controls in the Page hierarchy.

The exception is elements that aren't real elements, but special tags within another server tag, for example ContentTemplate tags. They don't need a runat="server" because the containing control will parse them.

When you don't want the server side ASP.NET to render a server side variable against us.

Generally speaking you don't use it when you don't need to manipulate the DOM element at the server side e.g. which are only used for layout purposes.

Without runat="server" there would also be no other way to make html controls server side controls. It does look like an odd thing, because you can't do runat="client".

So in summation you can't leave it out on any ASP .Net controls ever and it was probably the easiets and cleanest way to find all server side controls for the developers who created ASP .Net Web forms.

source: http://mikeschinkel.com/blog/whyrunatserverforaspnetpart2/

Tag runat="server" indicates that the code contained within the script block will run on the server (and not on the client). On execution, ASP.NET will create server-side objects that contain this code as well as an instance of the Page class to contain the controls defined inside the page as instances of their given type (System.Web.UI.WebControls.Textbox, for example). This server-side object will be invoked on user request and will execute code in response to events.

Create Control in Runtime

I need one label in runtime that time don't need runat="Server" is not required

Example

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
   {
    Label  lblNew = new Label();
    lblNew.ID ="lblnew";
    lblNew.Text ="Test";
    }
}

this code create label in runtime at page load event

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top