Live Chat Icon For mobile
Live Chat Icon

ASP.NET FAQ

Find answers for the most frequently asked questions
Expand All Collapse All

Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt’ go through the browser, the browser doesn’t update its history and if the user clicks Back, they go to the page previous to the source page.

Another way to pass values is to use something like a LinkButton. It posts back to the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the target page you can read the Session values as required.

Refer to Passing Values Between Web Forms Pages for more information.

Permalink

Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.

Below are the Code Migration Assistants

  • ASP to ASP.NET Migration Assistant
  • PHP to ASP.NET Migration Assistant
  • JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net

Permalink

Microsoft has designed The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.

The following Code Migration Assistants are discussed in the link below.

  • ASP to ASP.NET Migration Assistant
  • PHP to ASP.NET Migration Assistant
  • JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net

Also refer:

Permalink

Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio .NET, select the ‘Project | Copy Project’ menu. Then enter the URL and select the FrontPage web access method. The ‘Copy Project’ feature copies all of the necessary files to your ISP’s machine for your ASP.NET application to run.

You can also FTP your files to your ISP web server. But you must know which files to upload.
For more details refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on the Server Computer

Permalink

<script language='javascript'>
function SetFocus()
{
	// W3C approved DOM code that will work in all modern browsers	
	if (document.getElementById)
          		document.getElementById(’txt2’).focus();
     	else
     	// To support older versions of IE:
         	if (document.all)
            		document.all('txt2').focus();
    	return false;
}
</script>

<body MS_POSITIONING='GridLayout' onload='SetFocus()'>
<form id='Form1' method='post' runat='server'>
	Enter 1:
	<asp:TextBox ID='txt1' Runat='server' Width='50' />
	<br>
	Enter 2:
	<asp:TextBox ID='txt2' Runat='server' Width='50' />
	<br>
	<asp:Button id='Button1' runat='server' Text='Button1'></asp:Button>
</form>
</body>

Refer
Sample IE Code

Permalink

The Literal control is similar to the Label control, except the Literal control does not enable you to apply a style to the displayed text..


<div>
	<asp:Literal ID='Literal1' runat='server'></asp:Literal>
</div>

protected void Page_Load(object sender, EventArgs e)
{
	Literal1.Text = 'LiteralTextDemo';
}

Now the Resultant text will be in the format: LiteralTextDemo

Permalink

For VB.NET, go to path C:\Program Files\Microsoft Visual Studio .NET\Vb7\VBWizards\WebForm\Templates\1033

Change the following line in the existing WebForm1.aspx


<body MS_POSITIONING='[!output DEFAULT_HTML_LAYOUT]'>

to


<body>

For C#, go to path C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033

Change the following line in the existing WebForm1.aspx


<body MS_POSITIONING='[!output DEFAULT_HTML_LAYOUT]'>

to


<body>

Note:Before changing any templates it’s a good idea to make backup copies of them
Or rather than above approach you can change the behavior for new files on a per project basis in Visual Studio by:

  1. Right clicking on the project name (Ex: ‘WebApplication1)’ in Solution Explorer, and select ‘Properties’.
  2. From project properties window, under Common Properties>Designer Defaults>Page Layout change ‘Grid’ to ‘Flow’.
Permalink

Response.Redirect

  • Transfers the page control to the other page, in other words it sends the request to the other page.
  • Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302 response to the client, and the client goes where it’s told.

Server.Transfer

  • Only transfers the execution to another page and during this you will see the URL of the old page since only execution is transferred to new page and not control.
  • Occurs entirely on the server, no action is needed by the client

Sometimes for performance reasons, the server method is more desirable

Permalink

Yes. Place the DLL containing the type in the application root’s bin directory and ASP.NET will automatically load the DLL when the type is referenced. This is also what happens when you add a custom control from the toolbox to your web form.

Permalink

Suppose you have following file hierarchy:


default.aspx
Admin/login.aspx
Misc/testpage.aspx

And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.aspx) file. Then you can use

  • Response.Redirect (‘../default.aspx’)
  • Response.Redirect (‘../Misc/testpage.aspx’)
Permalink

Here is a sample login screen:


<TABLE id='Table1' cellSpacing='1' cellPadding='1' width='300' border='1'>
<TR>
<TD>
<asp:Label id='Label1' runat='server'>User Name</asp:Label></TD>
<TD>
<asp:TextBox id='txtUserName' runat='server'></asp:TextBox></TD>
<TD>
<asp:RequiredFieldValidator id='RequiredFieldValidator1' runat='server' ErrorMessage='*' ControlToValidate='txtUserName'></asp:RequiredFieldValidator></TD>
</TR>
<TR>
<TD>
<asp:Label id='Label2' runat='server'>Password</asp:Label></TD>
<TD>
<asp:TextBox id='txtPassword' runat='server'></asp:TextBox></TD>
<TD>
<asp:RequiredFieldValidator id='RequiredFieldValidator2' runat='server' ErrorMessage='*' ControlToValidate='txtPassword'></asp:RequiredFieldValidator></TD>
</TR>
<TR>
<TD></TD>
<TD>
<asp:Button id='btnLogin' runat='server' Text='Login'></asp:Button></TD>
<TD></TD>
</TR>
</TABLE>

VB.NET


Dim myconnection As SqlConnection
Dim mycmd As SqlCommand
Dim strSql As String
Dim myReader As SqlDataReader

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        myconnection = New SqlConnection('Server=localhost;uid=sa;password=;database=northwind;')
        strSql = 'Select * from usertbl where username=' & '’' & txtUserName.Text & '’' & ' and userpassword=' & '’' & txtPassword.Text & '’'
        mycmd = New SqlCommand(strSql, myconnection)
        myconnection.Open()
        myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
        If myReader.Read() Then
            Response.Write('Welcome')
        Else
            Response.Write('Access Denied')
        End If

End Sub

C#


SqlConnection myconnection ;
SqlCommand mycmd ; 
string strSql ;
SqlDataReader myReader ;
private void btnLogin_Click(object sender, System.EventArgs e)
{
	myconnection = new SqlConnection('Server=localhost;uid=sa;password=;database=northwind;');
	strSql = 'Select * from usertbl where username=' + '’' + txtUserName.Text + '’' + ' and userpassword=' + '’' + txtPassword.Text + '’';
	mycmd = new SqlCommand(strSql, myconnection);
	myconnection.Open();
	myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
	if (myReader.Read() ) 
	{
		Response.Write('Welcome');
	}
	else
	{
		Response.Write('Access Denied');
	}
}
Permalink
  • Server.Transfer is used to End the current weform and begin executing a new webform. This method works only when navigating to a Web Forms page (.aspx)
  • Server.Execute is used to begin executing a new webform while still displaying the current web form. The contents of both forms are combined. This method works only when navigating to a webform page(.aspx)
Permalink

The common cause for this error is specifying a control as a SqlParameter’s Value instead of the control’s text value.

For example, if you write code as below you’ll get the above error:

VB.NET


Dim nameParameter As SqlParameter = command.Parameters.Add('@name', SqlDbType.NVarChar, 50)
nameParameter.Value = txtName

C#


SqlParameter nameParameter = command.Parameters.Add('@name', SqlDbType.NVarChar, 50);
nameParameter.Value = txtName ;

To resolve it, specify the control’s Text property instead of the control itself.

VB.NET


nameParameter.Value = txtName.Text

C#


nameParameter.Value =txtName.Text;
Permalink

If some other default page comes higher in the list, adjust the default.aspx to be the number one entry inside the IIS configuration. If you have multiple websites inside IIS, make sure the configuration is applied on the right website (or on all websites by applying the configuration on the server-level using the properties dialog, configure WWW service).

Permalink

You can use either of these:

  • HttpContext.Current.Server.MachineName
  • HttpContext.Current.Request.ServerVariables[‘LOCAL_ADDR’]

The first one should return the name of the machine, the second returns the local ip address.

Note that name of the machine could be different than host, since your site could be using host headers

Permalink

The <%# %> is used for databinding where as <%= %> is used to output the result of an expression. The expression inside <%# %> will be executed only when you call the page’s or control’s DataBind method. The expression inside <%= %> will be executed and displayed as and when it appears in the page.

Permalink

A URL is the address of some resource on the Web, which means that normally you type the address into a browser and you get something back. There are other type of resources than Web pages, but that’s the easiest conceptually. The browser goes out somewhere on the Internet and accesses something.

A URI is just a unique string that uniquely identifies something, commonly a namespace. Sometimes they look like a URL that you could type into the address bar of your Web browser, but it doesn’t have to point to any physical resource on the Web. It is just a unique set of characters, that, in fact, don’t even have to be unique.

URI is the more generic term, and a URL is a particular type of URI in that a URL has to uniquely identify some resource on the Web.

Permalink

Use the namespace System.Globalization

VB.NET


Dim myString As String = 'syncFusion deVeloPer sUppOrt'
’ Creates a TextInfo based on the 'en-US' culture.
Dim TI As TextInfo = New CultureInfo('en-US', False).TextInfo
Response.Write(TI.ToTitleCase(myString))

C#


string myString = 'syncFusion deVeloPer sUppOrt';
// Creates a TextInfo based on the 'en-US' culture.
TextInfo TI = new CultureInfo('en-US',false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

For more details refer TextInfo.ToTitleCase()

Permalink

You can do this using assembly directives.


<%@ assembly src='test1.vb' %> 
<%@ assembly src='test2.vb' %> 

or

<%@ assembly src='test1.cs' %> 
<%@ assembly src='test2.cs' %> 

However, note that each source file will be compiled individually into its own assembly, so they cannot have dependencies on each other.

Permalink

Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed.
Many people prefer this since they don’t have to manually worry about compiling and messing with dlls — it just works.
Of course, the source is now on the server, for anyone with access to the server — but not just anyone on the web.

CodeBehind attribute doesn’t really ‘do’ anything, its just a helper for VS.NET to associate the code file with the aspx file.
This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone.
Now there is only a dll to deploy, no source, so it is certainly better protected, although its always decompilable even then.

Permalink

In the global.asax Application_error Event write the following code

VB.NET


Dim ex As Exception = Server.GetLastError().GetBaseException()
If TypeOf ex Is System.IO.FileNotFoundException Then
	’your code
	’Response.Redirect('err404.aspx')
Else
	’your code
End If

C#


Exception ex = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException)) 
{
	//your code
	Response.Redirect ('err404.aspx');
}
else 
{ 
	//your code
}
Permalink

In classic ASP, when a form is submitted the form values are cleared.
In some cases the form is submitted with huge information. In such cases if the server comes back with error, one has to re-enter correct information in the form. But submitting clears up all form values. This happens as the site does not maintain any state (ViewState).

In ASP .NET, when the form is submitted the form reappears in the browser with all form values. This is because ASP .NET maintains your ViewState.
ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user.
The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat=’server’> control.


<input type='hidden' name='__VIEWSTATE' value='dDwyNTA3OTU0NDM7Oz7t5TntzkOUeB0QVV6FT2hvQwtpPw==' /> 

If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState=’false’%> at the top of an .aspx page
If you do not want to maintain Viewstate for any control add the attribute EnableViewState=’false’ to any control.
For more details refer The ASP.NET View State

Permalink

This means that ASP.Net is not properly registered with IIS.

.Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe


       use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net  version.
       use the command: aspnet_regiis.exe -i ---> to install current asp.net version.

For Windows Server 2003, you must use aspnet_regiis -i -enable

This is because of the ‘Web Service Extensions’ feature in IIS 6

(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET ’hooks’ into IIS properly.’

Permalink

<asp:label id='Label2' runat='server'>Select a culture: </asp:label>
<asp:dropdownlist id='ddlCulture' runat='server' autopostback='True'></asp:dropdownlist>
<P></P>
<asp:label id='Label3' runat='server'>DateTime in Selected Culture</asp:label>
<asp:textbox id='TextBox1' runat='server'></asp:textbox>
<p>
<asp:label id='Label1' runat='server'></asp:label>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’Put user code to initialize the page here
	If Not Page.IsPostBack Then
            		Dim cInfo As CultureInfo
	           	For Each cInfo In CultureInfo.GetCultures(CultureTypes.SpecificCultures)
			ddlCulture.Items.Add(cInfo.Name)
	                Next
	End If
End Sub

Private Sub ddlCulture_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCulture.SelectedIndexChanged
	’ Get a CultureInfo object based on culture selection in dropdownlist
	Dim cInfo As CultureInfo = New CultureInfo(ddlCulture.SelectedItem.Text)
	’ Get a CultureInfo object based on Invariant culture 
	Dim cInfoNeutral As CultureInfo = New CultureInfo('')
	’ Display the datetime based on the formatting of the selected culture
       	TextBox1.Text = Convert.ToString(Now, cInfo.DateTimeFormat)
	’ Create a DateTime variable to hold the Invariant time
  	Dim dt As DateTime
	dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat)
     	’Convert the  datetime into a string for use in the SQL statement
	Label1.Text = '... WHERE ([Date] < ’' & _
	Convert.ToString(dt, cInfoNeutral.DateTimeFormat) & '’)'
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
		foreach(CultureInfo cInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
		{
			ddlCulture.Items.Add(cInfo.Name);
		}
	}
}

private void ddlCulture_SelectedIndexChanged(object sender, System.EventArgs e)
{
	       // Get a CultureInfo object based on culture selection in dropdownlist
	       CultureInfo cInfo  = new CultureInfo(ddlCulture.SelectedItem.Text);
	       // Get a CultureInfo object based on Invariant culture 
	       CultureInfo cInfoNeutral    = new CultureInfo('');
	       // Display the datetime based on the formatting of the selected culture
	       TextBox1.Text = Convert.ToString(DateTime.Now , cInfo.DateTimeFormat);
	       // Create a DateTime variable to hold the Invariant time
	       DateTime dt ; 
	       dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat);
	       //Convert the  datetime into a string for use in the SQL statement
	       Label1.Text = '... WHERE ([Date] < ’' +   Convert.ToString(dt, cInfoNeutral.DateTimeFormat) + '’)';
}
Permalink

VB.NET


Dim adate As DateTime = DateTime.Parse('06/24/2003')
Dim bdate As DateTime = DateTime.Parse('06/28/2003')
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & '<br>')
Response.Write(ts.TotalHours & ':' & ts.TotalMinutes & ':' & ts.TotalSeconds & ':' & ts.TotalMilliseconds)

C#


DateTime adate    = DateTime.Parse('06/24/2003');
DateTime bdate    = DateTime.Parse('06/28/2003');
TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);
Response.Write(ts.TotalDays.ToString () + '<br>');
Response.Write(ts.TotalHours.ToString() + ':' + ts.TotalMinutes.ToString() + ':' + ts.TotalSeconds.ToString() +  ':' + ts.TotalMilliseconds.ToString() );
Permalink

<TITLE id='Title1' runat =server ></TITLE>

VB.NET


’Declare
Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl

’In Page_Load
Title1.InnerText ='Page 1'

C#


//Declare 
protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;

//In Page_Load
Title1.InnerText ='Page 1' ;
Permalink

Clients do not report information back about where the user selects to save the content, so there isn’t an easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file path, and then you could specify the filename parameter for the content-disposition header. Still, the user is free to change that path when actually downloading.

Permalink

Absolute /Fully Qualified URLs:

  • Contain all information necessary for the browser(or other client program) to locate the resource named in the URL
    • This includes protocol moniker used( i.e http://, ftp://..etc..), Server’s Domain name or IP address and the file path
    • Absolute URL looks as http://localhost/syncfusion/page1.aspx

Relative URLs:

  • Only provide information necessary to locate a resource relative to the current document(document relative) or current server or domain(root relative)
    • Document relative URL – page1.aspx
    • Root Relative URL – /syncfusion/Admin/pagelog.aspx
Permalink

xxx is an event handler
src is the object that fires the event
e is an event argument object that contains more information about the event

An event handler is used when one object wants to be notified when an event happens in another object

Permalink

VB.NET


Dim stringUri As String = 'http://www.syncfusion.com/?id=1&auid=16'
Dim weburi As Uri = New Uri(stringUri)
Dim query As String = weburi.Query
Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)
Response.Write(weburl)

C#

 
string stringUri = 'http://www.syncfusion.com/?id=1&auid=16'; 
Uri weburi = new Uri(stringUri); 
string query = weburi.Query; 
string weburl = stringUri.Substring(0, stringUri.Length - query.Length);
Response.Write (weburl);
Permalink

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.