0% found this document useful (0 votes)
24 views

Interview Questions ASP.NET Web Forms

The document contains a comprehensive list of interview questions and answers related to ASP.NET Web Forms, covering topics such as the differences between Web Forms and MVC, the page life cycle, ViewState, event handling, and data binding. It explains key concepts and provides examples for implementing various features, including validation controls, Master Pages, and session management. Additionally, it outlines the roles of the Global.asax file and the differences between Server.Transfer and Response.Redirect.

Uploaded by

Nazif Ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Interview Questions ASP.NET Web Forms

The document contains a comprehensive list of interview questions and answers related to ASP.NET Web Forms, covering topics such as the differences between Web Forms and MVC, the page life cycle, ViewState, event handling, and data binding. It explains key concepts and provides examples for implementing various features, including validation controls, Master Pages, and session management. Additionally, it outlines the roles of the Global.asax file and the differences between Server.Transfer and Response.Redirect.

Uploaded by

Nazif Ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

INTERVIEW QUESTIONS

ASP.NET Web Forms Interview Questions

1.​ What is the difference between ASP.NET Web Forms and ASP.NET
MVC?
2.​ Explain the page life cycle in ASP.NET Web Forms.
3.​ What is ViewState in ASP.NET Web Forms? How does it work?
4.​ How can you manage the state of a page in ASP.NET Web Forms?
5.​ What are the different types of controls available in ASP.NET Web
Forms?
6.​ How would you implement validation in ASP.NET Web Forms?
7.​ What is the role of the Global.asax file in Web Forms?
8.​ How do you handle events in ASP.NET Web Forms?
9.​ Explain the difference between Server.Transfer and Response.Redirect
in Web Forms.
10.​ What is the use of the PostBack property in ASP.NET Web Forms?
11.​ How do you implement Master Pages in Web Forms?
12.​ Explain the concept of DataBinding in Web Forms and provide an
example.
13.​ What is the difference between a Literal control and a Label control in
Web Forms?
14.​ What are HTTP Handlers and HTTP Modules in Web Forms?
15.​ How would you manage session state in ASP.NET Web Forms?
16.​ Difference Between Repeater and GridView?
ASP.NET Web Forms

ASP.NET Web Forms is a web application framework developed by Microsoft for


building dynamic, data-driven websites. It uses an event-driven, drag-and-drop
model, allowing developers to create web pages using controls like buttons,
textboxes, and grids, while handling server-side logic in languages like C# or
VB.NET. Web Forms abstracts the complexities of HTTP and HTML, enabling easier
development of interactive applications. It uses features like ViewState to maintain
the state of controls between requests and supports a page life cycle with events
such as Page_Load and Page_Init.

1.What is the difference between ASP.NET Web Forms and ASP.NET MVC?

Ans:

Feature ASP.NET Web Forms ASP.NET MVC

Architecture Event-driven, Page MVC (Model-View-Controller)


Controller pattern pattern

Control Flow Handles events in page Action methods handle requests


lifecycle and responses

URL Structure Based on physical files Clean, SEO-friendly URLs


(.aspx)

ViewState Uses ViewState to maintain Stateless, no ViewState


state

Testability Limited due to tight coupling Highly testable with separation of


concerns

Data Binding Automatic binding with Manual data binding via HTML
controls helpers
Design Less flexible in HTML output Full control over HTML and output
Flexibility

Use Cases Rapid data-driven Customizable, testable,


applications SEO-friendly apps

2. Explain the page life cycle in ASP.NET Web Forms.

Ans:The ASP.NET Web Forms Page Life Cycle refers to the series of events
that occur when a page is requested and processed. Here’s a brief summary
of each phase:

1.​ Page Request: The page is requested by the user, and the ASP.NET
engine handles the request.
2.​ Initialization (Init): Controls are initialized, and their properties are set,
but they are not yet populated with data.
3.​ Load: Controls are loaded with data, and properties like values and
labels are set. If it's a postback, the controls retain previous values.
4.​ Postback Event Handling: User events (like button clicks) are handled.
This happens only if it's a postback.
5.​ Rendering: The page’s HTML output is generated, and the final HTML is
sent to the browser.
6.​ Unload: Resources are cleaned up after the page has been fully
rendered.

Key Concepts:

●​ ViewState: Keeps track of control values between postbacks.


●​ Postback: A form submission or action that triggers the server to
process the page again.

3.What is ViewState in ASP.NET Web Forms? How does it work?


Ans:ViewState in ASP.NET Web Forms is a mechanism used to preserve the state of
controls (such as values, properties, etc.) between postbacks. It enables the page to
remember the values of controls (e.g., TextBox, DropDownList) after the page is reloaded.

How it works:

●​ ViewState is stored in a hidden field (__VIEWSTATE) on the page.


●​ When a page is requested, the ViewState is sent from the client to the server,
and the server restores the values of controls from the ViewState during the
Load phase.
●​ During postback, the values entered in controls are automatically saved into
the ViewState, which is sent back to the server with the next request.

Key Points:

●​ Persists control data between requests.


●​ Stored in a base64-encoded string in the page's HTML.
●​ Enabled by default, but can be disabled for specific controls or globally for the
page.

4.How can you manage the state of a page in ASP.NET Web Forms?

Ans:In ASP.NET Web Forms, you can manage the state of a page using the
following methods:

1.​ ViewState: Retains control values between postbacks in a hidden field


on the page.
2.​ Session State: Stores user-specific data on the server across requests.
3.​ Application State: Stores global data shared across all users and
sessions.
4.​ Cookies: Stores small pieces of data on the client side.
5.​ Query String: Passes data in the URL between pages.
6.​ Hidden Fields: Stores data in the page's HTML, not visible to the user

5.What are the different types of controls available in ASP.NET Web


Forms?

Ans:In ASP.NET Web Forms, there are several types of controls available,
including:

1.​ Standard Controls:


○​ Button, Label, TextBox, DropDownList, RadioButton, CheckBox,
ListBox, GridView, Repeater, DataList, HyperLink, ImageButton, etc.
2.​ Web Controls:
○​ Controls that render HTML elements such as Panel,
Placeholder, Table, Literal, HyperLink, etc.
3.​ Validation Controls:
○​ Used for input validation, such as RequiredFieldValidator,
RangeValidator, RegularExpressionValidator,
CompareValidator, CustomValidator, and ValidationSummary.
4.​ Data Controls:
○​ Used for displaying and managing data, such as GridView,
Repeater, ListView, DetailsView, FormView, DataList, etc.
5.​ Rich Controls:
○​ Controls that provide advanced features, such as Calendar,
FileUpload, Image, AdRotator, MultiView, Wizard, etc.
6.​ HTML Controls:
○​ Basic HTML controls such as <input>, <textarea>, <select>,
etc., provided through ASP.NET Web Forms.
○​

6.How would you implement validation in ASP.NET Web Forms?

Ans:In ASP.NET Web Forms, validation can be implemented using Validation Controls.
These controls allow you to validate user input on the client side and server side.

Common Validation Controls:

1.​ RequiredFieldValidator: Ensures a field is not left empty.


2.​ RangeValidator: Validates if the input is within a specified range.
3.​ RegularExpressionValidator: Validates the input using a regular expression
(e.g., for email format).
4.​ CompareValidator: Compares the value of two controls (e.g., password and
confirm password).
5.​ CustomValidator: Allows custom validation logic.
6.​ ValidationSummary: Displays a summary of all validation errors.

How to Implement:

●​ Place validation controls next to the corresponding input controls.


●​ Set the ControlToValidate property to link the validator with the input control.
●​ Use ValidationGroup to group validators for specific sections of the page
(optional).
Example: code

<asp:TextBox ID="txtEmail" runat="server" />

<asp:RegularExpressionValidator ID="revEmail" runat="server"


ControlToValidate="txtEmail"ValidationExpression="^[\w-]+(\.[\w-]+
)*@([\w-]+\.)+[a-zA-Z]{2,7}$" ErrorMessage="Invalid email address"
/>

<asp:Button ID="btnSubmit" runat="server" Text="Submit"


OnClick="Submit" />

7.What is the role of the Global.asax file in Web Forms?

Ans:The Global.asax file in ASP.NET Web Forms is used to handle application-level


events and global configurations. It provides a central location for defining event handlers
that are triggered during the application's lifecycle.

Key roles of Global.asax:

1.​ Application Events:


○​ Application_Start: Triggered when the application starts.
○​ Application_End: Triggered when the application ends.
○​ Session_Start: Triggered when a new session starts.
○​ Session_End: Triggered when a session ends.
2.​ Routing and Request Handling:
○​ It can be used for custom request processing, such as error
handling or URL routing.
3.​ Global Filters:
○​ Allows setting up filters, such as custom logging or
authentication mechanisms.

Example:c# code

void Application_Start(object sender, EventArgs e)

{
// Code that runs on application startup

8.How do you handle events in ASP.NET Web Forms?

Ans:In ASP.NET Web Forms, events are handled by associating event handlers with
controls, such as buttons or dropdown lists. These events are triggered by user actions
like clicks, selections, or changes.

Steps to handle events:

1.​ Define an event handler in the code-behind (e.g., Button_Click, TextChanged).


2.​ Associate the event handler with the control's event in the markup or in the
code-behind.

Example:code

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />In


the code-behind:c# code

protected void btnSubmit_Click(object sender, EventArgs e)

// Handle the button click event

When the button is clicked, the btnSubmit_Click method is executed.

9.Explain the difference between Server.Transfer and Response.Redirect in Web


Forms.

Ans:Server.Transfer and Response.Redirect are both used for page navigation, but they differ in
the following ways:

1.​ Server.Transfer:
○​ Happens on the server side.
○​ URL in the browser does not change.
○​ No round-trip to the client, making it faster.
○​ Can pass data using Context.Items.
2.​ Response.Redirect:
○​ Happens on the client side.
○​ URL in the browser changes.
○​ Involves a round-trip to the client, making it slower.
○​ Data must be passed using query strings, session, or cookies.

Summary: Server.Transfer is faster and doesn’t change the URL, while


Response.Redirect causes a round-trip to the client and changes the URL.

10.What is the use of the PostBack property in ASP.NET Web Forms?

Ans:The PostBack property in ASP.NET Web Forms indicates whether the page is being
requested for the first time or is being processed after a form submission (postback).

●​ Page.IsPostBack returns true if the page is being loaded as a result of a


postback (e.g., after a button click), and false if it is being loaded for the first
time.

Usage:Used to prevent re-initialization of controls on a postback, saving processing time


(e.g., reloading data into controls only on the first page load).

Example:C# code

if (!IsPostBack)

// Code to execute only when the page is loaded for the


first time

11.How do you implement Master Pages in Web Forms?

Ans:In ASP.NET Web Forms, Master Pages are used to provide a consistent layout for
multiple pages in a website.

Steps to implement Master Pages:

1.​ Create a Master Page:


○​ Add a new Master Page (.master file) in your project.
○​ Define common elements like headers, footers, navigation menus, etc.,
in the master page.

Example: code​
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
2.Create Content Pages:

●​ Create pages (.aspx) that will use the master page.


●​ In the content page, set the MasterPageFile attribute to the master page file.

Example: code

<%@ Page MasterPageFile="~/Site.Master" Language="C#" %>

3.Add Content to ContentPlaceHolder:

●​ In the content page, use <asp:Content> tags to add content inside the master
page’s ContentPlaceHolder.

Example: code

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

<h1>Welcome to My Page!</h1>

</asp:Content>

Result:

The content pages will inherit the layout and elements defined in the master page,
providing a consistent structure across the site.

12.Explain the concept of DataBinding in Web Forms and provide an example.

Ans:DataBinding in Web Forms is the process of connecting UI controls (like GridView,


DropDownList) to data sources (like databases or collections) to display or manipulate
data dynamically. It can be Declarative (via <%# %> expressions) or Programmatic (using
DataBind() in the code-behind).

Example:code

<asp:GridView ID="GridView1" runat="server"


AutoGenerateColumns="True"></asp:GridView>

Code-Behind:C# code

protected void Page_Load(object sender, EventArgs e)

{
if (!IsPostBack)

var employees = new List<Employee>

new Employee { ID = 1, Name = "Alice", Dept = "HR" },

new Employee { ID = 2, Name = "Bob", Dept = "IT" }

};

GridView1.DataSource = employees;

GridView1.DataBind();

public class Employee

public int ID { get; set; }

public string Name { get; set; }

public string Dept { get; set; }

Result: A GridView displays the ID, Name, and Dept columns dynamically.

13.Explain the concept of DataBinding in Web Forms and provide an example.

Ans: Static Databind

DataBinding in Web Forms connects UI controls (e.g., GridView, DropDownList) to data sources
(e.g., databases, collections) for dynamic content display. It can be Declarative (using <%# %>
in markup) or Programmatic (using DataBind() in code-behind).

Example:code

<asp:GridView ID="GridView1" runat="server"


AutoGenerateColumns="True"></asp:GridView>
Code-Behind:code

protected void Page_Load(object sender, EventArgs e){

if (!IsPostBack)

GridView1.DataSource = new[] {

new { ID = 1, Name = "Alice", Dept = "HR" },

new { ID = 2, Name = "Bob", Dept = "IT" }

};

GridView1.DataBind();

Result: The GridView displays rows dynamically with ID, Name, and Dept columns.

Dynamic Data Bind

To bind data dynamically in Web Forms, you can connect your UI controls to dynamic
data sources such as a database or an API. Here's how you can achieve dynamic
data binding:

Example: Dynamic DataBinding with a Database

Step 1: Set Up the Markup

html

Copy code

<asp:GridView ID="GridView1" runat="server"


AutoGenerateColumns="True"></asp:GridView>

Step 2: Code-Behind to Fetch and Bind Data

csharp:code
using System;

using System.Data;

using System.Data.SqlClient;

public partial class DynamicDataBinding : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

BindGridView();

private void BindGridView()

string connectionString = "your_connection_string_here"; // Replace with your DB connection


string

string query = "SELECT ID, Name, Dept FROM Employees"; // Replace with your table and fields

using (SqlConnection conn = new SqlConnection(connectionString))

SqlDataAdapter adapter = new SqlDataAdapter(query, conn);

DataTable dataTable = new DataTable();

adapter.Fill(dataTable);

GridView1.DataSource = dataTable;

GridView1.DataBind();
}

Explanation

1.​ Data Source: A database table (e.g., Employees) is queried dynamically


using SQL.
2.​ Fetching Data: A DataTable is populated with the result of the SQL query.
3.​ Binding Data: The GridView is bound to the DataTable and updated with
DataBind().

Result

The GridView displays rows dynamically with data fetched from the database. Any
changes to the database (e.g., new rows, updated fields) will reflect in the UI after a
page refresh.

This approach works for other controls like DropDownList or Repeater with similar
methods for setting the DataSource and calling DataBind().

14.What are HTTP Handlers and HTTP Modules in Web Forms?

Ans:In ASP.NET Web Forms:

●​ HTTP Handlers are components responsible for processing specific types of


HTTP requests (like serving images or handling custom file extensions). They
implement the IHttpHandler interface and are mapped to particular file
extensions or URL patterns in the web.config.
●​ HTTP Modules are global components that intercept and process every HTTP
request before or after it reaches the handler. They implement the
IHttpModule interface and can be used for tasks like authentication, logging,
or modifying requests and responses across the entire application. They are
also configured in the web.config under the <modules> section.

Key Difference: Handlers process specific requests, while modules can globally
affect all requests in the application's lifecycle.

15. How would you manage session state in ASP.NET Web Forms?
Ans:In ASP.NET Web Forms, session state is used to store user-specific data across multiple pages during a
user's session. You can manage session state in several ways:

1.​ In-Proc (default): Stores session data in memory on the web server. Fast but not suitable for
web farms.
2.​ State Server: Stores session data on a separate server, enabling session sharing across
multiple web servers.
3.​ SQL Server: Stores session data in a SQL Server database, allowing persistence and session
sharing across multiple web servers in a web farm.
4.​ Custom Session State: Allows you to implement a custom storage mechanism for session
data.

You can configure session state in the web.config file:

xml: code

<system.web>

<sessionState mode="InProc" timeout="20" />

</system.web>

To use session:

●​ Set session variables: Session["username"] = "John";


●​ Retrieve session variables: string username = Session["username"].ToString();

Managing Session Lifetime: You can manage the session timeout and expiration through the
timeout attribute in web.config.

16. Difference Between Repeater and GridView?

Ans:

Feature Repeater GridView

HTML Control Full control over HTML structure Limited customization with
predefined layouts

Built-in Features No built-in features (e.g., paging, sorting) Supports paging, sorting,
editing, and deleting

Performance Heavier due to additional


Lightweight, faster features
Use Case Flexible layouts for custom designs Tabular data display with
minimal customization

Key Takeaway:

●​ Use Repeater for flexibility and lightweight requirements.


●​ Use GridView for quick tabular data with built-in functionality.

You might also like