.netASP.netInterview questions

ASP.net Interview Questions (Part-1)

In this article,We will discuss few ASP.net interview questions with answers for beginners and experienced professionals.

1.What is the Postback in ASP.NET?

A postback is a request sent from a client to server from the same page, user is already working with.

    • Add a new ASP.NET web form page to a project e.g. WebForm1.aspx.
    • View the page code in HTML Source view.
  • Look the form line of code.

<form id=”form1″ runat=”server”>;
It represents a server-side implementation of form control.

  • Now just run the application to see WebForm1.aspx page and view its source code. HTML source of the page will display form element as follows:
    <code>form id="form1" action="WebForm1.aspx" method="post"&gt;
  • You can see that an HTML form element generated with an HTTP method as “POST” and action=”WebForm1.aspx”. So, if a submit button is clicked, the page will postback to itself by default.
  • Following figure will also give you more understanding on ASP.NET Postback.

Postback in ASP.net

You can read more on postback vs Callback difference here.


2. Difference between ASP.NET WebForms and ASP.NET MVC?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In this approach, every page has it’s own controller i.e. code-behind file that processes the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this approach a common controller for all pages, processes the requests.

ASP.net web form ASP.net MVC
Page controller pattern that means an implicit controller (code behind) would process the request Front controller pattern that means an explicitcontroller would be there to process the request
web form has user controls for code reusability Partial views has code reusability
view and controllers are not separated view and controller are handled separately
stateful and view state is used to maintain state Stateless, so view state is not used
Has server control Has html helper
views are tightly coupled with business logic views and logics are separately managed
Master pages for constant look and feel MVC layouts for constant look and feel
Filebased urls and it needs physical files Route based urls and doesnot need a physical file. It depends on controller
Recommended for small scale applications Recommended for large scale applications



3.Please briefly explain ASP.NET Page life Cycle?

ASP.net Page Life Cycle

Initialization: Controls raise their Init event in this stage.Objects and variables are initializes for complete lifecycle of request.
LoadViewState: is a post back stage and loads the view state for the controls that enabled its view state property.

LoadPostBackData: is also a post back stage and loads the data posted for the controls and update them. 
Load: In this stage page as well as all the controls raise their Load event. Till this stage all the controls are initialized and loaded. In most of the cases, we are coding this event handler.
RaisePostBackEvent: is again a postback stage. For example, it’s raise against a button click event. We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.

You can see the detailed explanation on ASP.net page life cycle here


4.What is the difference between custom controls and user controls?

Custom controls are basically compiled code i.e. DLLs. These can be easily added to toolbox, so it can be easily used across multiple projects using drag and drop approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly couple with respect to User Interface and code. In order to use across multiple projects, we need to copy and paste to the other project as well.


5.Please briefly explain the usage of Global.asax?

Global.asax is basically ASP.NET Application file. It’s a place to write code for Application-level events such as Application start, Application end, Session start and end, Application error etc. raised by ASP.NET or by HTTP Modules.

There is a good list of events that are fired but following are few of the important events in Global.asax:

  • Application_Init occurs in case of application initialization for the very first time.
  • Application_Start fires on application start.
  • Session_Start fires when a new user session starts
  • Application_Error occurs in case of an unhandled exception generated from application.
  • Session_End fires when user session ends.
  • Application_End fires when application ends or time out.

You can read the detailed article here.


6.What is the concept of view state in ASP.NET?

  • ViewState of a webform is available only within that webform
  • ViewState is stored on the page in a hidden field called viewState. it will be lost if the user will navigate away from the page or if browser is closed
  • ViewState is used y all asp.net controls to retain their state across postback

You can read the difference between view state,session state and Application state here.


7.Difference between Response.Redirect and Server.Transfer?

Both Server.Transfer and Response.Redirect are ASP.NET objects and are used for navigation between web-pages. However, there are noticeable differences between these two techniques:
  • Response.Redirect() redirects the user to another web-page which may or may not be on thesame server. It can redirect the user to an external website on a different server.
  • Response.Redirect() updates the address bar and adds the updated URL to the browser history. User can click back on the browser to navigate to the previous page.
  • Response.Redirect() terminates the request with HTTP 302 status and client-side roundtrip. Client then navigates to the new address and the browser address bar and history updates. The client pays the cost of additional round-trips to the server on each request.
  • Form variables are are not transferred upon a call to Response.Redirect().
  • Server.Transfer() quits current execution of the web-page and redirects the user to another web-page on thesame server. It cannot send the user to an external website on a different server.
  • Server.Transfer() keeps the URL unchanged in the address bar. It happens entirely on the server side and the client browser’s address bar remains constant. User cannot click on back button on the browser to navigate to the previous page
  • Server.Transfer() reduces the server request and conserves server resources. It simply changes the focus on the Web Server and transfers the request. With Server.Transfer() there are less number of HTTP requests, which eases pressure on the Web Server and makes the application execute faster.
  • Developer can transfer Query Strings and form variables with a little bug-bashing. The Server.Transfer() method has a second parameter – preserveForm. If this is set to True, the existing query string and form variables will be available to the transferred page. Ex –Server.Transfer(“webpage2”, True);


8.What are the different types of Validation controls in ASP.NET?

In order to validate user input, ASP.NET provides validation server controls. All validation controls inherits from BaseValidator class which contains the common validation properties and methods like ControlToValidate, Enabled, IsValid, EnableClientScript, ValidationGroup,Validate() etc.

ASP.Net provides a range of validation controls:

  • RequiredFieldValidator validates required input.
  • RangeValidator validates the range. Validates that input is between the given range values.
  • CompareValidator validates or compares the input of a control with another control value or with a fixed value.
  • RegularExpressionValidator validates input value against a defined regular expression pattern.
  • CustomValidator allows to customize the validation logic with respect to our application logic.
  • ValidationSummary displays all errors on page collectively.


9.What are HttpHandlers and HttpModules in ASP.NET?

HttpHandler: ASP.NET Engine uses HttpHandlers to handle specific requests on the basis of it’s extensions. ASP.NET Page Handler handles all requests coming for (.aspx) pages. We can define our own custom HttpHandler to handle a specific request with a specific extension, say .jpeg, .gif, or .ahmad. But there will always be only one handler for a specific request.

HttpModuleASP.NET Engine uses HttpModules to inject some specific functionality along with ASP.NET default functionality for all incoming requests regardless of its extensions. There are a number of built-in modules already available in ASP.NET HTTP Pipeline. But we can write our own custom HTTP module to perform some additional functionality (for example, URL rewriting or implementing some security mechanism) for all incoming requests.
We have discussed HttpHandler and HttpModule in detailed here.

10.What are the types of Authentication in ASP.NET?

There are three types of authentication available in ASP.NET:

  • Windows Authentication: This authentication method uses built-in windows security features to authenticate user.
  • Forms Authentication: authenticate against a customized list of users or users in a database.
  • Passport Authentication: validates against Microsoft Passport service which is basically a centralized authentication service.


11.What are Session state modes in ASP.NET?

ASP.NET supports different session state storage options:

  • In-Process is the default approach. It stores session state locally on same web server memory where the application is running.
  • StateServer mode stores session state in a process other than the one where application is running. Naturally, it has added advantages that session state is accessible from multiple web servers in a Web Farm and also session state will remain preserved even web application is restarted.
  • SQLServer mode stores session state in SQL Server database. It has the same advantages as that of StateServer.
  • Custom modes allows to define our custom storage provider.
  • Off mode disables session storage.


12.Hyperlink Vs LinkButton in ASP.NET?

A Hyperlink redirects to a given URL identified by “NavigateURL” property but a LinkButton which actually displays a Hyperlink style button causes a postback to the same page but it doesn’t redirect to a given URL.


13.Globalization Vs Localization

When we need to build an application that work for multiple cultures e.g en-US, ar-SAetc, this process of designing and building applications that work for more than one cultures is called globalization. However, customizing an application for a specific culture is localization. Both globalization and localization normally go together.


14. How to access information about a user’s locale in ASP.NET?

User’s locale information can be accessed through System.Web.UI.Page.Culture property.
15.Cache Management in ASP.NET?

ASP.NET provided support for Cache Management in almost all versions. In .NET Framework 3.5 and older, the support for caching was provided through classes available in System.Web.Caching. But this support was limited to System.Web meaning for ASP.NET Web Applications only. Now, with .NET Framework 4.0 and later, this support is enhance to non-Web Applications also by providing APIs in System.Runtime.Caching.

  •  ASP.NET supports three types of Caching:
    • Page Output Caching
    • Partial Page Caching
    • Data Caching


16.Difference between Culture and UICulture properties in ASP.NET?

CultureInfo class plays an important role for localizing our application pages. Culture is specific in localizing non-visual parts of the page like DateTime, Currency, number formatting etc.

while UICulture is specific in localizing visual part of a webpage like Language being used to display the contents of the web page.



17.What is State Management?

ASP.net State Management

HTTP is a stateless protocol by nature. So, we need some mechanism to preserve state (i.e. state of a webpage, a control or an object etc.) between subsequent requests to server from one or more clients. and this mechanism is referred as State Management in ASP.net

You can read more detailed article on state management here.



18.What are the State Management Techniques used in ASP.NET?

State Management techniques used in ASP.NET can be categorized in two types:

  1. Client-Side State Management
    • View State
    • Control State
    • Hidden Fields
    • Cookies
    • Query String
  2. Server-Side State Management
    • Application State
    • Session State
    • Profile Properties
    • Cache
You can read more detailed article on state management here.
19.What is ViewState? or Explain ViewState as State Management Technique?
  • ViewState is one of the Client-Side State Management techniques that provides page-level state management, which means state is preserved between subsequent requests to same page.
  • By using this technique, state of the page along with its controls is stored in a hidden form field  i.e. “__VIEWSTATE” and this field is again available on server when page is posted back with HTTP Request.
  • ViewState data is encoded in Base64 String encoded format.
  • ViewState can be enabled or disable at different levels:
    • Control Level
      • ViewState for a specific control can be enabled or disabled by setting EnableViewState
    • Page Level
      • ViewState for a specific control can be enabled or disabled by setting EnableViewState
    • Application Level
      For whole application, we can enable/disable views in configuration file.



20.What is the difference between Application and Session State?

Application state is basically a common data repository for an application’s all users and their all sessions. On the other hand, Session state is specific to a single user session. You can read more detailed explanation here.


21.What is the difference between Session.Clear() and Session.Abandon() in ASP.NET?

Session is a Collection and it stores data as Key/Value pair.

Session.Clear() clears all the session values but doesn’t destroy the Session.

Session.Abandon() destroys the session object.

In otherwords ,Session.Clear() is like deleting all files inside a folder (say “Root”) but Session.Abandon() means deleting the “Root” folder.


22.Can we Enable/Disable ViewState?

Yes, we can enable/disable view state at different levels.

In another article, we have discussed how to enable/disable view state. You can read it here.


23.Difference between Local and Global resources?

Resources for a localized ASP.NET application can be stored locally as well as globally.

Local resources are specific to web page and stored in a folder App_LocalResources.

It can be accessible to that specific page only. Global resources are accessed by almost all application pages and stored in App_GlobalResources folder.


24.What is the difference between Label Control and Literal Control?

A Label control in ASP.NET renders text inside <span> tags while a Literal Control renders just the text without any tags.
With Label controls we can easily apply styles using it’s CssClass property, however, if we don’t want to apply style/formatting, it’s better to go for a Literal control.


25.What is the difference between var and dynamic?

var dynamic
Introduced in C# 3.0 Introduced in C# 4.0
Statically typed – This means the type of variable declared is decided by the compiler at compile time. Dynamically typed – This means the type of variable declared is decided by the compiler at run time.
var type of variables are required to be initialized at the time of declaration or else they encounter the compile time error: Implicitly-typed local variables must be initialized. No need to initialize at the time of declaration.
e.g., var str=”I am a string”; e.g., dynamic str;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string. str=”I am a string”; //Works fine and compiles
Errors are caught at compile time. Errors are caught at runtime
Since the compiler knows about the type and the methods and properties of the type at the compile time itself Since the compiler comes to about the type and the methods and properties of the type at the run time.
Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, the compiler has all the information related to the type Intellisense help is not available for dynamic type of variables since their type is unknown until run time. So intellisense help is not available. Even if you are informed by the compiler as “This operation will be resolved at run-time”.
will  throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infera type from the value. Will compile



26. Difference between String and StringBuilder?

String StringBuilder
A string (namespace: System.String ) is a sequential collection of Unicode characters that represents text A StringBuilder (System.Text.StringBuilder) represents a mutable string of characters. This class cannot be inherited.
String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of stringtype in memory. StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating new instance for every time.it will update string at one place in memory doesnt create new space in memory.
Any operation that appears to change the string, it creates a new instance of stringtype in memory Any operation that appears to modify or append new string, it doesn’t create a new instance of string typein memory
The maximum size of a String object in memory is 2 GB (about 1 billion characters). The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters.
 Example:string strMyValue = “Hello Visitor”;
// create a new string instance instead of changing the old one
strMyValue += “How Are”;
strMyValue += “You ??”;
Example:StringBuilder sbMyValue = new StringBuilder(“”);
sbMyValue.Append(“Hello Visitor”);
sbMyValue.Append(“How Are You ??”);
string strMyValue = sbMyValue.ToString();
String is slower as compare to string builder object when we deals with large size of strings StringBuilder is faster as compare to string object when we deals with large size of strings
String is efficient when we deals with static or smaller size of string means we don’t need to modify later on StringBuilder is efficient when we deals with dynamic or larger size of string means we want to modify that string later on
Although a string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. However after boxing the comparison happens on string instances.


27.What is web Farm and Web Garden in ASP.net?

  • Multiple web servers with same configuration  hosted in one environment is known as web farm
  • In Web garden a single machine has multiple asp.net worker processes running simultaneously
  • You can read more on Web Farm and Web Garden here.


28. What is Adrotator control in ASP.net?

Adrotator control is used to display random ads.the ads information can be stored in an xml file or in database tables.

The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is called the advertisement file.

The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in the AdvertisementFile and the Target property respectively. You can read more detailed explanation here.


29.What is Impersonation in ASP.net?

Impersonation is an act of a user to pretend itself to be another user. By default, ASP.NET executes application code using the same user account as that of ASP.NET process i.e. Network Service. But with impersonation enabled, it executes code with the windows identity of the user making the request. You can read more on Impersonation here.


30.What is Caching and what are the benefits of using it?

Performance has always been a concern for web based applications. So, Caching is a mechanism that improve performance for an application by storing data in memory for fast access. When the application will access data from Cache (i.e. in-memory) instead of fetching it from original data store (may be a database), it will definitely improve performance.But Caching benefits are not limited to performance only, it also improve application Scalability as well as Availability.

  • Load on server is reduced when data is fetched from Cache instead of original source, thus improving scalability of an application.
  • Caching normally keep serving application data even if the original source is temporarily down, thus improving availability of an application.

© 2015, www.techkatak.com. All rights reserved.