asp.netformsrunat

How can you tell if form runat=server has been set?


When coding an Asp.Net page, you generally add a runat attribute in the aspx:

<form id="form1" runat="server">

Is it possible to tell in the code behind if the user hasn't done this i.e. they only did this:

<form id="form1">

Here the form has the id "form1" but in my case I don't know this. Code behind such as this is what I am looking for:

if(Page.HasForm)
{
}

Solution

  • You can only ever have one form tag with "runat=server" on it per .aspx page. All you have to do is to check to see if Page.Form is null or not. If it's null, then there's no form that has been marked to runat server.

    if (Page.Form != null)
    {
    
    }
    

    It's the runat="server" part that makes the .aspx page process an element and create a corresponding object on the server side. If a component is not running on the server, then it's not added to the page's control hierarchy.