Wednesday , 16 April 2014
Home / ASP .Net Tutorials / ASP .Net Interview Question Answers – 6

ASP .Net Interview Question Answers – 6

ASP .Net Interview Question Answers – 6

Q1: How do I send a new page to the user?
A1: The Redirect method of the Response object is one of the most common ways to send users a new Web page:

Response.Redirect(“Page2.aspx”)

You might also know of the similar method, Server.Transfer:

Server.Transfer(“Page2.aspx”)

But do you know the difference between these two methods? The server-side Response.Redirect statement sends a command back to the browser to request the next page from the server. This extra round-trip is often inefficient and unnecessary, but this battle-tested standard works reliably and consistently. By the time Page2 is requested, Page1 has been flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using one of the techniques outlined later in this article.

The more efficient Server.Transfer method simply renders the next page to the browser without the extra round trip. Variables can stay in scope and Page2 can read properties directly from Page1 because it’s still in memory. This technique would be ideal if it wasn’t for the fact that the browser is never notified that the page has changed. Therefore, the address bar in the browser will still read “Page1.aspx” even though the Server.Transfer statement actually caused Page2.aspx to be rendered instead. While this bit of sneakiness can occasionally be a good thing from a security perspective, it often causes problems related to the browser being out of sync with the server. For example, if the user reloads the page, the browser will request Page1.aspx instead of the true page (Page2.aspx) that they were viewing.

In most cases, Response.Redirect and Server.Transfer can be used interchangeably. But in some cases, efficiency or usability may prompt you to use one instead of the other.

Q2: How do I pass values between pages?
A2: Context and QueryString are common ways to pass values between pages in ASP.NET. Which one is best depends on the particular circumstances.

The QueryString has been a common way of passing data around the Internet since before ASP was even invented. Before a variable value is placed on the QueryString, it should be encoded to ensure problematic characters (such as spaces and symbols) are interpreted correctly as data:

‘Page1.aspx appends the user’s name to the QueryString

Dim sName As String

sName = Server.UrlEncode(txtName.Text)

Response.Redirect(“Page2.aspx?Value=” & sName)

‘Page2.aspx parses the value from the QueryString

Dim sName As String

sName = Request.QueryString(“Value”)

Response.Write(“Your name is ” & sName)

When the user arrives at Page2, the data is appended to the URL. Therefore, the address listed in their browser will look something like this:

http://localhost/MyWebSite/MyPage.aspx?Value=Steve+Orr

The Context object isn’t as well known as the Session object, but it should be — the syntax is the same; simply replace the word “Session” with the word “Context”:

‘Page1.aspx stores value in context before transferring

Context.Items(“UserName”) = txtName.Text

Server.Transfer(“Page2.aspx”)

‘Page2.aspx retrieves the value from Page1’s context

Dim sName As String

sName = Context.Items(“UserName”).ToString

Response.Write(“Your name is ” & sName)

One of the main differences between Context and Session is that Context only stays in scope until the page is sent to the browser. Therefore, this is one of the few examples where Server.Transfer must be used instead of Response.Redirect. Because Response.Redirect would cause the context to go out of scope, the data would be lost. Context uses server memory more sparingly than Session variables, so it’s often preferable except in cases where data needs to be stored across the user’s entire visit.

Before ASP.NET 1.0, posting data from one page to another was comparable to the QueryString (aka “get”) technique. ASP.NET 1.x made this technique less practical than it used to be because there was no longer any simple way to post data from one page to another. The new philosophy was that pages were meant to post back to themselves.

As ASP.NET 2.0 comes into focus and frees us from most cross-page posting limitations, this technique starts to become more favorable again. For example, by setting the PostBackURL property of a button control on Page1.aspx, you can have it post all form values (including any hidden text fields) to Page2.aspx. This technique requires no server-side code in Page1.aspx:

‘Page2.aspx retrieves the posted form value

Dim sName As String

sName = Request.Form(“TextBox1”).ToString

Response.Write(“Your name is ” & sName)

Q3: How do I pass data to a user control?
A3: User controls often contain many controls within them. Sometimes it’s handy to be able to set the properties of those sub controls from within the page’s code-behind. I’ve witnessed much confusion about how to do this. Here’s a best-practice solution in three easy steps:

Step 1: In the user control’s code-behind file, create a public method or property that the page will call. In the following example, the user control contains a Label control. This example sets the encapsulated label’s Text property with the supplied parameter value:

Public Sub SetLabelText(ByVal val As String)

Label1.Text = val

End Sub

Step 2: Within the code-behind class of the page, declare a strongly-typed reference to the user control:

Protected WithEvents MyControl1 As MyUserControl

This control is automatically instantiated by ASP.NET, so you don’t need the New keyword.

Step 3: Now you can call the user control’s custom method from within the page:

MyControl1.SetLabelText(“Value set from page code behind”)

Q4: How do I pass data back to the page from a user control?
A4: You could take an approach similar to the previous solution; that is, by calling a method on a strongly-typed reference to the page from within the user control:

CType(Page, UserControlHostPage).MyCustomSub()

However, this creates a circular reference, which is generally considered to be a questionable design decision because of object-oriented principles such as encapsulation. Such tightly coupled relationships are discouraged. One reason is that it would tie the control to this particular page, thereby limiting reuse. There are ways around that with Interfaces and such, but that’s where things start to get rather sloppy. It is considered preferable for child objects to raise events instead of directly referencing the parent. To raise an event, the event must first be declared within the user control’s class:

Public Event ButtonClicked()

Then the event can be raised to the page with a single line of code:

RaiseEvent ButtonClicked()

The page can then handle the control’s event with a simple declaration and event handler:

Protected WithEvents MyUserControl1 As MyUserControl

Private Sub MyUserControl1_ButtonClicked() _

Handles MyUserControl1.ButtonClicked

Response.Write(“User control’s button was clicked.”)

End Sub

Q5: How do I pass a value between two user controls?
A5: This functionality can be achieved by combining the techniques for passing values to and from user controls. The page acts as the referee, permitting or denying communication between the controls as it deems appropriate. Controls can raise events to the page, which the page might decide to pass to properties or methods of other controls within the page.

Q6: How do I pass a value between an ASP.NET 2.0 page and its master page?
A6: The routine for passing data around remains similar for new ASP.NET constructs, such as Master Pages. From the aspect of passing data around, the master page acts as a control within the page. So, as with the earlier page/control techniques, to call a public method located within a page’s master page, you must cast the master reference to the exact class name:

Dim MP As MyMasterPage

MP = CType(Me.Master, MyMasterPage)

MP.MyPublicMasterPageSub()

‘The above 3 lines can alternatively be simplified to one:

CType(Me.Master, MyMasterPage).MyPublicMasterPageSub()

To pass data from the master page to the page, the master page should raise an event to the page:

Public Event MasterPageButtonClicked()

Then the event can be raised to the page with a single line of code:

RaiseEvent MasterPageButtonClicked()

The page can handle the event just as if it were coming from a user control:

Private WithEvents _MyMasterPage As MyMasterPage

Private Sub MyMasterPage_ButtonClicked() _

Handles _MyMasterPage.ButtonClicked

Response.Write(“Master page raised button click event.”)

End Sub

The only difference is that you need to assign the master page reference to the _MyMasterPage variable because ASP.NET (Beta 2) doesn’t do this for you:

MyMasterPage = CType(Me.Master, MyMasterPage)

That line of code could go in the Page_Load event — or nearly anywhere else that’s convenient.

Q7: How do I store global variables?
A7: Any good developer will tell you that global variables should be used sparingly. Even so, sometimes they are the most efficient way to get data everywhere it is needed. There are a few ways to store variable values globally in ASP.NET. The most common approaches involve use of the Application, Cache, and Session objects.

The Application object has been available since the inception of ASP, and its sturdy foundations are as reliable now as they were back then. The Application object stores data that is meant to be shared across all user sessions — so don’t put data in it that applies only to a particular user. One notable syntax quirk is the need to lock the application item before setting it. This prevents more than one page request from writing to the same item at the same time. Don’t forget to unlock the item again after you’ve set it:

‘Page1.aspx places the data in Application State

Application.Lock()

Application(“MyValue”) = Textbox1.Text

Application.UnLock()

Response.Redirect(“Page2.aspx”)

‘Page2.aspx retrieves the value from Application State

MyString = Application(“MyValue”).ToString

The similar (but more modern) Cache object has a simplified syntax that negates the need for manually locking and unlocking. Notice how similar the syntax is compared to the ViewState approach mentioned earlier:

‘Page1.aspx Caches the value

Cache(“MyValue”) = Textbox1.Text

Response.Redirect(“Page2.aspx”)

‘Page2.aspx retrieves the value from the Cache

MyString = Cache(“MyValue”).ToString

Like the Application object, the Cache object stores data that is meant to be shared across all user sessions — so don’t put data in it that applies only to a particular user. However, the Cache object has richer functionality than the Application object. The Cache object can automatically expire cached content after specified time periods or once memory consumption has reached a peak. Cache items can also be set to expire whenever a given file changes or when a related Cache item changes. Cache values can be prioritized and automatically refreshed.

The Session object has been around since the early days of ASP. This classic and reliable technique is great for storing a user’s data during the length of their visit to your Web site:

‘Page1.aspx stores the user’s name in Session state

Session(“UserName”) = txtName.Text

Server.Transfer(“Page2.aspx”)

‘Page2.aspx retrieves the user’s name from Session state

MyString = Session(“UserName”).ToString

ASP.NET tracks each user’s session, helping to ensure that one user’s data is never displayed to another user. By default, each session value is stored in server memory. If you multiply each session variable times the number of active users in your Web site you might realize that memory usage can add up very quickly. For this reason, Web applications that need to be highly scalable tend not to use session variables much, if at all. For smaller applications, the convenience of Session variables is simply irresistible.

What if you want to store variables across a user’s entire visit but for scalability reasons you don’t want to use Session variables? There’s really no simple answer, but the most obvious fallbacks are cookies and databases. Cookies are tidbits of data stored in the user’s browser; therefore, they don’t really use any server memory. However, cookies have gotten a bad rap over the years, so many users have them turned off. For this reason I recommend that you don’t rely on them. Another technique is to store the data in a back-end database and retrieve required data upon each page request. Although this conserves the Web server’s memory, it increases network and database traffic. A more complex technique is to create your own custom business objects that cache the data in ways that are efficient for your specific application.

Session state can be configured to be automatically stored in a SQL Server database, or it can be configured to be stored centrally in a state server within a server farm.

By default, a user’s session ends 20 minutes after their last page request and their data goes out of scope, freeing it from memory.

Q8: How do I store a value between PostBacks?
A8: You might have noticed that variables’ values you’ve carefully set in a page’s code-behind are wiped out when the page posts back to itself. Although this can be annoying and confusing to developers accustomed to Windows application development, it can be easily solved with a couple lines of code. Simply store the variable’s value in ViewState before PostBack, and it will be waiting there for you to retrieve after the PostBack:

‘Store the value in ViewState before PostBack
ViewState(“MyVariable”) = MyString

‘Retrieve the value from ViewState after PostBack
MyString = ViewState(“MyVariable”).ToString

You might be interested to know that ASP.NET stores this (and all other ViewState values) in an encoded hidden text element within the page’s form. Because this data is transferred between the client and server between each PostBack, you shouldn’t fill it with any more data than is necessary. Storing a few simple values won’t be a problem, but storing large DataSets and large structures tends to be more problematic from a performance perspective.

Leave a Reply