How can you tell if form runat=server has been set? - asp.net

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)
{
}

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.

var v = this.Form.TagName; //gets the name of the form that is maked as runat.
Of course if its not maked as runat then your code behind won't run anyway...

When you code in C# or Visual Basic in the code page, you will not have access to the object that do not have the runat=server option set.
You can easily access all the controls from a page using the me.controls page or something of the sort (I don't know the exact code but it's close to this) and check the type of the control to get the form.
Why do you need to know that? If a page does not have a runat=server form, it can't really be used as a server page.

You'd be able to access the form from the codebehind:
Response.Write(form1.Name);
Without the runat="server", you'd just get a compiler error.

Related

using postbackurl to pass variables without referencing ctl00$MainContent

I'm hoping there's a cleaner way of doing this. My source page markup has some simple inputs and a submit button:
<asp:TextBox runat="server" ID="TBPostDateFrom" placeholder="From" />
<asp:TextBox runat="server" ID="TBPostDateTo" placeholder="Present" />
...
<asp:Button ID="BtnDetailedResults" PostBackUrl="~/Auth/ResultsDetail.aspx" runat="server" Text="View Detailed Results" />
On my target page, I'm trying to reference those controls and use them as datasource select parameters. So far the only way I've found to do that is to use the long asp generated names "ctl00$MainContent$TBPostDateFrom" and "ctl00$MainContent$TBPostDateTo":
SDSDetailedResults.SelectParameters.Add("PDFrom", Request.Form["ctl00$MainContent$TBPostDateFrom"]);
SDSDetailedResults.SelectParameters.Add("PDTo", Request.Form["ctl00$MainContent$TBPostDateTo"]);
Is there a way I can reference those controls without using the long ct100$...? Or a way to reference the controls directly? I'm guessing if sometime down the road I change my master page, or content controls, these references would get messed up.
I've tried adding using adding the ClientIDMode=Static to the inputs like:
<asp:TextBox runat="server" ID="TBPostDateFrom" placeholder="From" ClientIDMode="Static" />
But that appears to only change the ID. On my target page, I'm still unable to reference it without using the ct100$....
I've also tried using the Page.PreviousPage method, but the objects end up empty:
if (Page.PreviousPage != null)
{
//post date
TextBox PostDateFrom = (TextBox)Page.PreviousPage.FindControl("TBPostDateFrom");
TextBox PostDateTo = (TextBox)Page.PreviousPage.FindControl("TBPostDateTo");
//at this point both PostDateFrom and PostDateTo are empty, if I do this:
SDSDetailedResults.SelectParameters.Add("PostDateFrom", PostDateFrom.Text);
SDSDetailedResults.SelectParameters.Add("PostDateTo", PostDateTo.Text);
// I get an IIS error saying the object references dont' exist, or are null
}
}
Thanks in advance, any help or guidance is much appreciated!
For a search page, I would recommend using the QueryString to pass information to your later page, rather than trying to reference the controls from the previous page.
This will be especially useful if you want to use this functionality from different technologies. You won't have to worry about where the request came from.
SearchPage.aspx:
//Button Click:
var page = "ResultsDetail.aspx";
var url = String.Format("{0}?TBPostDateFrom={1}&TBPostDateTo={2}", page, TBPostDateFrom.Text, TBPostDateTo.Text);
Response.Redirect(url);
ResultDetails.aspx:
var from = DateTime.Parse(Request.QueryString["TBPostDateFrom"]);
var to = DateTime.Parse(Request.QueryString["TBPostDateTo"]);
//Do search based on parameters
For more information: MSDN - How to: Pass Values Between ASP.NET Web Pages

When isn't runat="server" used in asp.net?

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.
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";
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

Question about the "runat" attribute in ASP.NET?

I went through this thread but couldn't understand much. I am very new to ASP/HTML/Server-side programming.
I tried running this code on a .aspx file:
<form id="form1" action="Default.aspx">
<div>
<asp:Label ID="lblName"></asp:Label>
</div>
</form>
And I got an error when I tried to use this in the CodeFile:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = "123";
}
"lblName does not exist".
But if I use runat="server" attribute with the label, then this code works.
Also, is there any concept of nesting the runat attribute. e.g, If I specify runat=server for the form above, will all my controls inside the form automatically be configured to run at server? How does this attribute work?
In which case would I be required to specify runat=server for the and for the tag? How does the server-side know that the label is inside the form if I don't have a form object at server side? Or am I missing something?
Any element marked with runat="server" lets the framework know that this will be a control on the server side. This article has more details:
Exploring the Runat Attribute
Nope, there is no such nesting available in ASP.NET, you have to specify "runat" to every control that you want to use in code behind and that is part of ASP.NET web library.
Because ASP.NET can only recognize difference between client side tag (the html that runs on browser) and server side tag with help of "runat"

RegisterClientScriptBlock without form tag

After trying to understand why client code is not rendered in a page (injected by user control) I found this link, it turns out you must have a form tag for it to work (Page.RegisterClientScriptBlock did declare this but ClientScriptManager.RegisterClientScriptBlock which I use does not say anything regarding this).
I am using Visual studio 2005.
Does anyone know if this has been solved?
Edit:
To clarify, I want my control to add javascript code to the head section of the page without having to use the
<form runat="server"
I have tried adding it using:
HtmlGenericControl x = new HtmlGenericControl("script");
x.InnerText = "alert('123');";
Page.Header.Controls.Add(x);
But this did not work for me.
As far as I know this functions the same in current versions, you can test it very simply though.
Update
per discussion in the comments, the only "workaround" that I could think of would be for your to manually insert the script into the "head" section of the page on your own, using a runat="server" declaration on the Head element.
Got it!
My mistake was not doing it in the OnPreRender method (I used the Render method).
Now all that is needed is - like Mitchel Sellers wrote, set the header to runat server and than add to it's controls:
HtmlGenericControl x = new HtmlGenericControl("script");
x.InnerText = GetScriptSection();
Page.Header.Controls.Add(x);
Thanks for pointing me to the right direction!
The MSDN Page for registerclientscriptblock here says:
The client-side script is emitted just
after the opening tag of the Page
object's <form runat= server> element.
The script block is emitted as the
object that renders the output is
defined, so you must include both tags
of the <script> element.
If you do not want to include a form, than you will basically need to build your own implementation of it.
Minor clarification for anyone seeing this:
The form tag must have the runat="server" attribute set, e.g.
<form id="theform" runat="server">
Just placing a regular HTML form tag in the page will not help.

Html control and Server control can be used in single aspx page

I need help on this following aspx code
aspx Code:
<asp:Label ID ="lblName" runat ="server" Text ="Name"></asp:Label>
<asp:TextBox ID ="txtName" runat ="server"></asp:TextBox>
Consider this is my aspx page content. I am going to populate the values for the TextBox only after the postback from server. But the label is also posting to the server (runat="server") even though it's not necessary. Should I write my code like this to save time from server with less load.
Corrected Code:
<label id ="lblNames">Name</label>
<asp:TextBox ID ="txtName" runat ="server"></asp:TextBox>
Only my server control will send to the server for postback and not my HTML control which has a static value.
Please suggest whether this is the correct way of coding.
If you take the runat='server' out of the <label> element then it won't be parsed as a server control. If you're not going to do anything with lblNames from the server then it is perfectly okay to leave it out.
If you're not doing anything with the label server-side, then just use a <span>. It'll end up as the same html at the browser.
.net label controls are rendered as html label elements and do not get posted back to the server. Labels just don't post back. The server control allows you to manipulate the properties of the control in code however which is very useful.
There is nothing wrong with using html tags as well in your aspx/ascx page though if you don't need any programmatic control of the element.

Resources