Why do I have to specify runat="server" on all my ASP.NET controls when it is a mandatory attribute and server is the only option available in my limited knowledge of ASP.NET, and I get an error if I don't use it?
I do understand that I can optionally use it on my HTML tags, and I do understand the client/server paradigm and what it is actually specifying.
Is it a redundant tag that could just be implied by the control being an ASP.NET control, or is there an underlying reason?
I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being runat="server" or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.
This conversation was had on Mike Schinkel's Blog between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):
[...] but the importance of <runat="server"> is more for consistency and extensibility.
If the developer has to mark some tags (viz. <asp: />) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <runat="server"> attribute, this is negated.
It continues:
If <runat=client> was required for all client-side tags, the parser would need to parse all tags and strip out the <runat=client> part.
He continues:
Currently,
If my guess is correct, the parser
simply ignores all text (tags or no
tags) unless it is a tag with the
runat=server attribute or a “<%”
prefix or ssi “<!– #include… (...)
Also, since ASP.NET is designed to
allow separation of the web designers
(foo.aspx) from the web developers
(foo.aspx.vb), the web designers can
use their own web designer tools to
place HTML and client-side JavaScript
without having to know about ASP.NET
specific tags or attributes.
I usually don't like to guess, but I'm going to on this one...
If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.
So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.
Remember those weird ads?
Related: Article from The Register with some .NET history.
Not all controls that can be included in a page must be run at the server. For example:
<INPUT type="submit" runat=server />
This is essentially the same as:
<asp:Button runat=server />
Remove the runat=server tag from the first one and you have a standard HTML button that runs in the browser. There are reasons for and against running a particular control at the server, and there is no way for ASP.NET to "assume" what you want based on the HTML markup you include. It might be possible to "infer" the runat=server for the <asp:XXX /> family of controls, but my guess is that Microsoft would consider that a hack to the markup syntax and ASP.NET engine.
Microsoft Msdn article The Forgotten Controls: HTML Server Controls explains use of runat="server" with an example on text box <input type="text"> by converting it to <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.
In short, to enable programmatic access to the HTML element add runat="server" to it.
My suspicion is that it has to do with how server-side controls are identified during processing. Rather than having to check every control at runtime by name to determine whether server-side processing needs to be done, it does a selection on the internal node representation by tag. The compiler checks to make sure that all controls that require server tags have them during the validation step.
HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control.
It's there because all controls in ASP .NET inherit from System.Web.UI.Control which has the "runat" attribute.
in the class System.Web.UI.HTMLControl, the attribute is not required, however, in the class System.Web.UI.WebControl the attribute is required.
edit:
let me be more specific. since asp.net is pretty much an abstract of HTML, the compiler needs some sort of directive so that it knows that specific tag needs to run server-side. if that attribute wasn't there then is wouldn't know to process it on the server first. if it isn't there it assumes it is regular markup and passes it to the client.
I think that Microsoft can fix this ambiguity by making the compiler add runat attribute before the page is ever compiled, something like the type-erasure thing that java has with the generics, instead of erasing, it could be writing runat=server wherever it sees asp: prefix for tags, so the developer would not need to worry about it.
If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.
As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".
If #JonSkeet is around anywhere, he will probably be able to provide a much better answer.
When submitting the data to ASP.NET Web server the controls mentioned as Runat = “server” will be represented as Dot Net objects in Server Application. You can manually type the code in HTML controls or else can use Run As Server option by right clicking in design view.
ASP.NET controls will automatically get this attribute once you drag it from toolbox where usually HTML controls don't.
Pretty redundant attribute, considering the "asp" tag is obviously an ASP element and should be enough to identify it as a server side accessible element.
Elsewhere however it used to elevate normal tags to be used in the code-behind.
I just came to this conclusion by trial-and-error:
runat="server" is needed to access the elements at run-time on server side.
Remove them, recompile and watch what happens.
Any tag with runat=server is added as server control in Page and any html content between is handled as LiteralControls which are also added to Page controls collection.
runat="Server" indicates a postback to the server will occur for the HTML "control."
Web Forms use postback constantly to signal the server to process a page control event.
.NET MVC pages DO NOT use postback (except for a form "submit"). MVC relies on JQUERY to manage the page on the client side (thus bypassing the need for a lot of postback messages to the server).
So:
.NET Web Forms... use "runat" attribute a lot in the page markup.
.NET MVC hardly ever uses "runat" attribute in the page markup.
Hope this helps clarify why runat is necessary...
Related
I am trying out with asp.net . One thing i was surprise is that in our design code we don't used general <html>,<body> etc. but we used <asp:content> , <asp:button> etc. well i tried to find it out why but ended upon the abstract msdn pages . So please help me on this one
Tags with <asp:... tag prefix means they are "server side controls", which means:
they are accessible to your program on the server side (events, parameters, etc.) and by client side script (e.g. JavaScript)
they will be "rendered" (output when running/"translated to") as standard HTML tags when you actually run your web site
As an example, while you are building your web page/s the tag <asp:textbox runat="server" id=foo... will output as <input type="text" id="foo when you run the ASP.net application in a browser.
You can create a simple web page, run it in a browser, then VIEW SOURCE to see this "translation" at work.
So while you are developing/designing your web application, ASP.Net will provide you with what they call "controls" (e.g. button controls, label controls, etc.). They will all be translated into standard HTML tags/elements at runtime.
The above relates to ASP.Net technology called "Web Forms".
You can start with it - its a bit easier to program against. When you get more advanced and/or prefer to do more "bare metal" standard HTTP POST/GET, then you can look into ASP.Net MVC/Razor - this ASP.Net architecture will let you use standard HTML and pretty much control everything (which also means you need to know how to control 'everything').
There's nothing wrong with using HTML tags in ASP.NET pages, as long as you use runat="server" on them of course. I like to use a bit of both, dependent upon what it is. I suppose a benefit of using HTML tags means that you become more comfortable with the HTML and do not depend on the ASP.NET syntax.
On the other hand, in some cases, it would be an incredibly laborious task to actually write ALL of the HTML in order to replicate a control. Something like a complex DataGrid with all the events would be an absolute nightmare to write the pure HTML/JavaScript for. Using the ASP.NET control & syntax makes it much quicker and cleaner in that scenario.
I am not new to ASP.net. Actually, I am not even learning it. But, I was recently evaluating some Web sites and saw that awful <form runat="server" ..> that wraps the whole page and contains all other tags. The question: Is that valid HTML? It is 2012 and talks about semantic Web, accessible Web, etc. is hot. What do you think of it?
It is syntax-wise valid HTML. But I agree it's a bit 'outdated' a form and some hidden fields, etc. as ViewState.
Also it can be quite cumbersome to work when you want to use more forms on the page (using JQuery f.i.).
Take a look at ASP.Net MVC, it solves the problem. You have full control over the HTML and does not need a form tag around the page. It does not use asp.net server controls.
The the HTML5 specification isn't too restrictive and allows most elements to nest within a form, but does state
The form element represents a collection of form-associated elements,
some of which can represent editable values that can be submitted to a
server for processing.
So it would seem to me that if the element isn't form-associated, it shouldn't really be there.
So far, all the web pages I met contain at most one <form> tag. Why not multiple ones? I can not think of reasons why multiple forms can't coexist within the same web page.
Also, to be specific to ASP.NET - why are all the server controls are placed within the <form> tag? Why not place them somewhere else?
Plus,
I noticed that in an .aspx file, the <form> tag has the runat=server attribute, while a normal server control such as Button also has one. So it seems the <form> is also a server control. But strangely enough, I cannot find it in the Visual Studio Toolbox.
There can be multiple forms, with hacks.
It is indeed a shortcoming of WebForms. In ASP.NET MVC you can implement as many forms as you want (and it is valid & correct behavior of web pages).
The reason all server controls are placed inside <form> tag is to allow the WebForms engine to recognize them, load their values & save their values from/to the ViewState. Almost all infrastructure of control management in WebForms is based on the idea that a tag contains everything you access from the code-behind.
As pointed out, this is one of the shortcomings of WebForms. I do want to point out, additionally, that with cross-page posting and validation groups, you can typically reach your desired behavior (for most "multi-form" solutions).
Regarding the additional question: the <form runat="server"> is parsed as HtmlForm class behind the scenes, which inherits from HtmlControl like any other HTML element with runat="server".
Unlike any other HtmlControl though, there can exist only one instance per page and it does not appear in the toolbox as it's added automatically to every new Form you create, so it's quite pointless.
Yes, it can be done - by creating a custom HtmlForm object and toggling the forms as needed. I've just answered a similar question here (with code):
Paypal Form Ruins My ASP.NET webforms layout -> How to Solve?
many non server forms - you can , but only one runAt Server form
i also found this :
A server-side form tag is the tag which has a runat="server" attribute. If this attribute
is missing, then it's a typical HTML form tag. The conclusion is that you are allowed to use
multiple form tags on a page, as long as only one has the runat="server" attribute. The
disadvantage of the form that doesn't have this attribute, is that view state won't work
(meaning form values will disappear when using the back/forward browser buttons). It's a
small price to pay if you really need multiple forms on a page.
Take master page & set design.
Take one form in master page.
Second form take in contain place holder.
In contain place holder in only for write form tag (not use)
Add aspx page & design second form but not write form tag only for control put
Take button click event fire code write
This is proper way of two form
I would like to understand how can I use jQuery to work with asp.net and css.
When I'm writing asp.net code and for example I'm adding to a page DropDownList, I can't see it in the source when I'm opening source of a page in web browser. Instead of dropdownlist I can see select tag. When does the "magic" is done to change asp.net tag to select?
What is more I can't see my CSS classes names added to asp.net tags. There are some kind of differen CSS class names. But when I'm opening developer tools in IE, I can see CSS class names, which are same as in my definition.
And the last thing. What names of a tags sould I use in jQuery to traverse page which was developed in asp.net. Shoud I use a tags which I see in the source code of a page in a browser or can I ask jQuery about asp.net tags? What about CSS classes? Why I can't see them in a source of a page in a browser? Can use my names of a CCS classes under jQuery queries?
Please, can anybody explain me how does this three technologies work together?
When does the "magic" is done to change asp.net tag to select?
Most of "magic" you're wondering about is done by ASP.NET controls, which are designed to generate the markup that is sent to the browser.
When a request is received, the application iterates over each control, calling its Render method (inherited from the Control class), which allows each control to generate the markup they represent.
Following your example, the DropDownList control generates a <select> tag. As a ListControl, it uses the ListItem controls to create the <option> tags within.
Another would be the GridView, which generates a <table> using GridViewRow controls for <tr> and various HTML Controls, such as TableCell for <td> and <th>, to create the rest of the markup.
Shoud I use a tags which I see in the source code of a page in a browser or can I ask jQuery about asp.net tags?
No, jQuery/JavaScript have no knowledge of server-side control names, only the markup they generate. So, rather than searching for $('DropDownList'), you'd search for $('select').
What is more I can't see my CSS classes names added to asp.net tags. There are some kind of differen CSS class names.
By "CSS Names," do you mean IDs? I'm sorry to ask, but CssClass attributes shouldn't change in value from server-side to client-side, just in name -- CssClass to just class.
IDs, on the other hand, are prefixed to ensure their uniqueness throughout the page, including a prefix of the MasterPage and ContentPlaceHolder names, if they're used. For this reason, I'd steer away from trying to use IDs to apply CSS to server-side controls, using classes instead.
Now, the end of the ID should remain as the ID you gave in server-side, so you should still be able to find the element in jQuery using the Attribute Ends With Selector [name$='value']:
# ASP
<asp:DropDownList ID="AnyGivenDropDown" runat="server" />
# HTML (generated)
<select id="ctl00_PageContents_AnyGivenDropDown"></select>
# JavaScript
$('select[id$="_AnyGivenDropDown"]');
Otherwise, I'd stick to classes to find the controls you're looking for:
# ASP
<asp:DropDownList ID="AnyGivenDropDown" CssClass="anygiven" runat="server" />
# HTML (generated)
<select id="ctl00_PageContents_AnyGivenDropDown" class="anygiven"></select>
# JavaScript
$('select.anygiven');
# CSS
.anygiven { }
The "magic" happens in the render event of the asp.net page lifecycle. Asp.net server controls all render as standard html element(s). The most important difference is that you can access them and their values on the server side. WebControls also have a CssClass property that when rendered becomes the class attribute of the HTML element.
The id can be a bit tricky when working with jQuery and CSS. This is because depending on the controls hierarchy they may have a clientID such as ctl100_containerID_myControl instead of myControl. To overcome this in jQuery when you reference a control you can refrence it by its ClientID like so:
$('#<%=myControlID.ClientID%>')
This is serverside that will write the client side ID of the control after it is rendered.
ASP.NET: High-level web development framework. When you create a web form in .NET, the framework will work together with the IIS handlers and create (hopefully) valid HTML that will work with your server-side code during postbacks.
JQUERY: This will allow you to perform client-side scripting such as calculation, validation, and most notably AJAX, etc. This is basically just a wrapper for a simpler and easier-to-read version of javascript.
CSS: Takes the HTML and makes it pretty.
All three technologies work very well together if you know what you're doing.
I'm not sure if that's what you're looking for, but it sounds like you might want to invest in some beginner's literature.
Surely the fact that they're declared beginning with "<asp:" is enough to infer they're server controls? Or is it just included for completeness (so they look similar to the server control declaration of <input runat="server" for example). Or is there some special reason?
It just always bugs me that the compiler tells me I've missed it off when I do so accidentally. Kind of like the thinking behind "var" - if the compiler knows what it is.. why bother expecting me to state it?
Taken from this forum thread:
Internet Explorer supports DHTML
behaviors.
[The asp:control syntax] does not mean server
control. You can create client DHTML
component that has namespace and will
run on the client machine. Also,
namespaces are allowed in XHTML and
techically you can use asp namespace
for something else on a client, if you
wish. Runat="server" prevents
namespace clash. If element has no
runat="server" attribute, it will be
sent to the client browser unchanged.
Therefore, you can use HTML components
(HTCs) in ASP.NET pages as well.
Have a look here
http://msdn.microsoft.com/workshop/author/behaviors/howto/creating.asp
http://msdn.microsoft.com/workshop/author/behaviors/overview.asp
Mike Schinkel also has a blog post exploring why runat=server is necessary.