0% found this document useful (0 votes)
63 views37 pages

ASP.NET Question Bank and Answers

The document is a question bank for ASP.NET covering various topics including transfer objects, data binding, app_code folder, response objects, and the differences between skin and CSS files. It also discusses the ASP.NET page life cycle, advantages of ASP.NET, types of controls, and the benefits of themes over CSS. Additionally, it includes details on disconnected mode architecture in ADO.NET.

Uploaded by

italiyaharshil78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views37 pages

ASP.NET Question Bank and Answers

The document is a question bank for ASP.NET covering various topics including transfer objects, data binding, app_code folder, response objects, and the differences between skin and CSS files. It also discusses the ASP.NET page life cycle, advantages of ASP.NET, types of controls, and the benefits of themes over CSS. Additionally, it includes details on disconnected mode architecture in ADO.NET.

Uploaded by

italiyaharshil78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ASP.

NET QUESTION BANK


Q1: Answer the following questions: (2 Marks each)

1. What is transfer object?


→ Definition:
A Transfer Object (DTO) is a simple C# class that is used to carry data
between layers of an application (like from database → business logic → UI).
It usually contains only properties (getters/setters) and no business logic.

Example:
Suppose you have a User table in the database. Instead of passing your
entire entity (which may have extra info or methods), you can use a DTO:
// Transfer Object (DTO)
public class UserDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}

2. What is Data Binding in [Link]?


→Data Binding in [Link] is the process of connecting UI elements
(controls) like GridView, DropDownList, TextBox, etc., with a data source
(such as a database, collection, or object) so that data can be displayed,
updated, and synchronized automatically.
Example (Binding a GridView to a Database)
// Code-behind (C#)
1|Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("your_connection_string");
SqlCommand cmd = new SqlCommand("SELECT Id, Name, Email FROM
Users", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
[Link](dt);

[Link] = dt;
[Link]();
}
}

3. Why we use the app_code folder?


→The App_Code folder is a special folder in [Link] Web Site projects
where you place reusable code files such as classes, business logic, utility
functions, data access code, etc.
[Link] automatically compiles everything inside App_Code into a single
assembly, and then you can use that code throughout your website without
extra configuration.

4. Define Response Object.


→The Response object in [Link] is part of the HttpResponse class.
It represents the server’s response to the client (browser) and is used to
send output, control headers, cookies, and redirect requests.
Uses of Response Object
2|Page
• Send Output to Browser
• Redirect to Another Page
• Set Cookies
• Change Content Type

5. What is the difference between skin and css file?



Feature Skin File (.skin) CSS File (.css)
Defines the look and feel of Defines the style of HTML
Purpose [Link] server controls (e.g., elements (e.g., <div>, <p>,
Button, TextBox). <h1>).
Applies to [Link] Web Server Applies to all HTML elements
Scope
Controls only. on the web page.
Stored in a separate CSS file,
Stored inside the App_Themes
Storage usually in a Styles folder or
folder in [Link].
linked via <link>.
Control-based (e.g., Selector-based (e.g., .btn {
Syntax
<asp:Button> style definition). color: red; }).
Applied automatically when the Must be linked in the <head>
Application
control is rendered. section of the page.

6. List out the different file extensions of [Link] files.


→ Different File Extensions in [Link]
Here’s a list of commonly used [Link] file extensions:
• .aspx → [Link] Web Form page
• .ascx → User Control file
• .asmx → Web Service file
• .ashx → HTTP Handler file

3|Page
• .axd → Special handler file (e.g., [Link], [Link])
• .browser → Browser definition file
• .sitemap → Site navigation file
• .skin → Theme/skin file for controls
• .master → Master Page file
• .config → Configuration file (e.g., [Link], [Link])
• .cs / .vb → Code-behind files (C# or [Link])
• .resx → Resource file for localization/globalization

7. Write the use of Range Validator.


→The RangeValidator control is used to check whether the input value of
a control lies within a specified range (minimum and maximum values).
It works with numeric, string, and date ranges.

Example: Numeric Range


<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator
ID="RangeValidator1"
runat="server"
ControlToValidate="txtAge"
MinimumValue="18"
MaximumValue="60"
Type="Integer"
ErrorMessage="Age must be between 18 and 60">
</asp:RangeValidator>

4|Page
8. Differentiate dataset and data reader.

Feature DataSet DataReader
Connected architecture
Disconnected architecture
Nature (needs continuous
(works offline).
connection to DB).
Can hold multiple tables at Reads data from one
Data Storage
once (in-memory cache). table/query at a time.
Allows forward and backward
Navigation Forward-only, read-only.
navigation.
Slower due to overhead Faster as it reads data
Performance
(stores more data). directly from DB.
Allows insert, update, delete
Data Only reads data, cannot
in memory and later sync
Manipulation modify.
with DB.
When working with complex
When fast, read-only,
Best Use data (multiple tables,
forward access is needed.
relations).

9. What is the importance of [Link]?


→The [Link] file in [Link] defines application-level and session-
level event handlers (like Application_Start, Session_Start,
Application_Error), making it important for initialization, error handling, and
global settings.

5|Page
Q2: Answer the following questions: (5 or 7 Marks each)

1. Explain page life cycle of [Link] in detail.


→ Page Life Cycle of [Link]
When a user requests an [Link] page (e.g., [Link]), it goes through a
series of stages/events before the final HTML is sent to the browser.

Main Stages of [Link] Page Life Cycle


1. Page Request
o Occurs when a page is requested by the browser.
o [Link] decides whether to serve the page from cache or start
the full life cycle.

2. Start
o Page properties such as Request and Response are set.
o Determines whether the request is a postback (form submission)
or a new request.

3. Page Initialization (Init event)


o All controls on the page are initialized and assigned unique IDs.
o No values are restored yet.

6|Page
4. Load ViewState
o Restores control properties from the hidden __VIEWSTATE field (if
postback).
o Ensures that controls maintain values between postbacks.

5. Load (Page_Load event)


o Control properties are loaded with data.
o This is the stage where you usually write code to set values in
controls.

6. Postback Event Handling


o If the request is a postback, events such as Button_Click,
TextChanged, etc., are executed.

7. PreRender
o Final changes to the page or controls can be made before
rendering.
o Last chance to modify content before output is generated.

8. Render
o The page and its controls generate the final HTML that will be sent
to the browser.

9. Unload
o Cleanup stage.
o Page and control objects are disposed.
o Resources such as database connections are released.

7|Page
Diagram (for clarity in exams)
Page Request → Start → Init → Load ViewState → Load → Postback Events →
PreRender → Render → Unload

Example (Page_Load & Button_Click)


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
[Link] = "Welcome to [Link] Page Life Cycle!";
}
}

protected void Button1_Click(object sender, EventArgs e)


{
[Link] = "Button was clicked!";
}

2. What is ASP .NET? Explain advantages of ASP .NET in detail


→[Link] is a server-side web application framework developed by
Microsoft.
It is part of the .NET platform and is used to build dynamic web pages,
applications, and services.
• It supports multiple programming languages like C# and [Link].
• It runs on top of the Common Language Runtime (CLR), which means
developers can write secure and scalable applications.
• Modern version: [Link] Core (cross-platform, high performance).

8|Page
Advantages of [Link]
1. Separation of Code and Design
o Code (C# or [Link]) is placed in the code-behind file (.cs), and
design (HTML/ASPX) is separate.
o Makes development and maintenance easier.

2. Rich Server Controls


o Provides built-in controls like GridView, DropDownList, Repeater,
and Calendar.
o These controls reduce coding effort and improve productivity.

3. State Management
o [Link] provides mechanisms like ViewState, Session,
Cookies, and Application State to maintain user data across
requests.

4. Security
o Provides built-in authentication and authorization (Forms
Authentication, Windows Authentication).
o Supports role-based security and membership providers.

5. Scalability and Performance


o Uses compiled code (not interpreted like classic ASP).
o Features like caching, early binding, and JIT compilation improve
performance.

6. Cross-Language Support
o Any .NET language (C#, [Link], F#) can be used for development.

9|Page
o Makes it flexible for different teams.

7. Web Services and API Support


o Supports building SOAP-based Web Services (.asmx) and
RESTful APIs ([Link] Web API).
o Allows integration with other applications and platforms.

8. Built-in Caching
o [Link] has output caching, data caching, and fragment caching
to enhance performance by reducing database calls.

9. Cross-Platform ([Link] Core)


o [Link] Core applications can run on Windows, Linux, and
macOS.
o Suitable for cloud and microservices architecture.

3. List types of control used to create ASP .NET page. Explain TreeView
control in detail.
→ Types of Controls in [Link]
[Link] provides several types of controls to build dynamic web pages:
1. HTML Controls
o Standard HTML elements (<input>, <button>, <table>) that can be
run on the server by adding runat="server".
o Example:
o <input type="text" id="txtName" runat="server" />
2. Web Server Controls
o Rich set of controls provided by [Link].
o Examples: TextBox, Button, DropDownList, GridView, TreeView.

10 | P a g e
o Automatically render HTML and support events.
3. Validation Controls
o Used for input validation.
o Examples: RequiredFieldValidator, RangeValidator,
CompareValidator.
4. Rich Controls / Data Controls
o Used to display and manage data.
o Examples: GridView, DataList, DetailsView.
5. Navigation Controls
o Used for site navigation.
o Examples: Menu, TreeView, SiteMapPath.

TreeView Control in [Link]


Definition
The TreeView control is a navigation control in [Link] that displays data in
a hierarchical (tree-like) structure with expandable/collapsible nodes.

Features
• Supports hierarchical data binding (XML, SiteMap, database).
• Provides expand/collapse functionality.
• Can be used for menus, directories, categories, etc.
• Supports checkboxes for node selection.

Example
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>

11 | P a g e
<asp:TreeNode Text="Home"
NavigateUrl="~/[Link]"></asp:TreeNode>
<asp:TreeNode Text="Products">
<asp:TreeNode Text="Electronics"
NavigateUrl="~/[Link]"></asp:TreeNode>
<asp:TreeNode Text="Clothing"
NavigateUrl="~/[Link]"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Contact Us"
NavigateUrl="~/[Link]"></asp:TreeNode>
</Nodes>
</asp:TreeView>
This will create a tree menu with Home, Products (expandable:
Electronics, Clothing), and Contact Us.

Binding with SiteMap (Example)


<asp:TreeView ID="TreeView2" runat="server"
DataSourceID="SiteMapDataSource1">
</asp:TreeView>

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />


This automatically loads navigation links from [Link].

4. What are the advantages of themes over CSS. Explain various ways to
apply skin file.
→ Advantages of Themes over CSS in [Link]
While CSS is used to style HTML elements, [Link] Themes (with Skin
files) provide additional advantages:
12 | P a g e
1. Server-Side Integration
o Themes and Skins are [Link] aware. They can apply styles
directly to server controls (e.g., Button, TextBox), not just HTML
tags.
2. Consistency Across Application
o A theme can include CSS, Skin files, and Images in one package,
ensuring a consistent look throughout the entire application.
3. Control-Level Styling (Skins)
o Skins let you define default properties for [Link] controls (like
Font, BackColor, BorderStyle) which CSS alone cannot do.
Example skin:
<asp:Button runat="server" ForeColor="White" BackColor="Blue" Font-
Bold="true" />
4. Separation of Design and Logic
o Developers can focus on code while designers can work on
Themes separately.
5. Runtime Switching
o Themes can be changed dynamically at runtime for
personalization (e.g., Dark/Light mode).

Ways to Apply a Skin File


A Skin file (.skin) is stored inside a Theme folder (e.g.,
App_Themes\MyTheme\[Link]) and contains property settings for
server controls.
There are multiple ways to apply it:

1. Page Level (Theme Attribute in @Page Directive)


<%@ Page Language="C#" Theme="MyTheme" %>
Applies the theme only to that page.

13 | P a g e
2. [Link] Level (Global Application Theme)
<configuration>
<[Link]>
<pages theme="MyTheme" />
</[Link]>
</configuration>
Applies the theme to all pages in the application.

3. Programmatically (Code-Behind at Runtime)


protected void Page_PreInit(object sender, EventArgs e)
{
[Link] = "MyTheme";
}
5. Write a note on disconnected mode architecture
→ Note on Disconnected Mode Architecture
Definition
Disconnected mode architecture in [Link] allows applications to work
with data without maintaining a continuous connection to the database.
It uses the DataSet / DataTable to fetch data, work with it locally, and later
update the database in bulk.

Key Features of Disconnected Mode


1. Uses DataSet / DataTable
o Data is stored in memory after fetching from the database.
o DataSet can hold multiple tables and relationships.
2. No Continuous Connection Required

14 | P a g e
o Database connection is opened only to fetch data and to save
updates back.
o Saves resources and improves scalability.
3. XML Support
o DataSet can read/write XML, making it portable across
applications.
4. Data Manipulation
o Allows insert, update, delete operations locally.
o Changes are tracked using a DataAdapter and can be
synchronized with the database.

Example (C# with [Link] Disconnected Mode)


using [Link];
using [Link];

SqlConnection con = new SqlConnection("connection_string");


SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", con);

// Create DataSet
DataSet ds = new DataSet();

// Fill DataSet (disconnected)


[Link](ds, "Students");

// Work with data locally


foreach (DataRow row in [Link]["Students"].Rows)
{

15 | P a g e
[Link](row["Name"]);
}

// Update database later


SqlCommandBuilder cb = new SqlCommandBuilder(da);
[Link](ds, "Students");

6. Differentiate between DataSet and DataReader. Explain Read() method of


DataReader with example
→ Difference between DataSet and DataReader
Feature DataSet DataReader
Works in Disconnected mode Works in Connected mode
Mode (no continuous DB connection (requires continuous DB
needed). connection).
Stores data in memory Provides forward-only,
Data Storage
(multiple tables, relationships). read-only access to data.
Random access to data (can Sequential access (row by
Data Access
read, search, update rows). row, forward only).

16 | P a g e
Feature DataSet DataReader
Suitable for large data Best for fast, read-only
Data Volume
manipulation and caching. operations.
Can modify data locally and
Cannot modify data (read-
Updates update DB later via
only).
DataAdapter.
XML Support Can read/write data as XML. No XML support.
Slightly slower (overhead of Faster (direct, forward-only
Performance
storing in memory). stream).

Read() Method of DataReader


Definition
The Read() method of DataReader is used to advance the DataReader to
the next record.
• It returns true if there are more rows.
• It returns false when no more rows exist.

Example in C#
using System;
using [Link];

class Program
{
static void Main()
{
string conStr = "Data Source=.;Initial Catalog=SchoolDB;Integrated
Security=True";

17 | P a g e
SqlConnection con = new SqlConnection(conStr);

SqlCommand cmd = new SqlCommand("SELECT StudentID, Name


FROM Students", con);

[Link]();
SqlDataReader reader = [Link]();

while ([Link]()) // Moves row by row


{
[Link]("ID: " + reader["StudentID"] + ", Name: " +
reader["Name"]);
}

[Link]();
[Link]();
}
}

7. List various validation controls and explain any two in detail.


→ Validation Controls in [Link]
[Link] provides several built-in validation controls to ensure that the data
entered by the user is valid before it is processed.
List of Validation Controls
1. RequiredFieldValidator

18 | P a g e
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator
5. CustomValidator
6. ValidationSummary

Explanation of Any Two Validation Controls


RequiredFieldValidator
• Ensures that the user does not skip an input field.
• Used to make a field mandatory.
• Example:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="rfvName"
runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required!"
ForeColor="Red">
</asp:RequiredFieldValidator>
Here, if the user leaves the txtName empty and submits, the error
message will be displayed.

RangeValidator
• Ensures that input value falls within a specific range.
• Can validate numeric, date, or string ranges.
• Example:
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
19 | P a g e
<asp:RangeValidator
ID="rvAge"
runat="server"
ControlToValidate="txtAge"
MinimumValue="18"
MaximumValue="60"
Type="Integer"
ErrorMessage="Age must be between 18 and 60!"
ForeColor="Red">
</asp:RangeValidator>

8. What is master page? What is its importance? How to create nested


master page. Explain with suitable example.
→ What is a Master Page in [Link]
A Master Page is a template for other pages in an [Link] application.
• It defines a common layout and design (header, footer, navigation
menu) for multiple web pages.
• Content pages can then fill in the placeholders defined by the master
page.

Importance of Master Page


1. Consistency
o Ensures a uniform look and feel across all pages (e.g., same
header, footer, menus).
2. Reusability
o You can define a layout once and reuse it across multiple pages.
3. Ease of Maintenance
20 | P a g e
o Changes made in the master page automatically reflect on all
content pages.
4. Separation of Layout and Content
o Designers can focus on layout in the master page.
o Developers can focus on page-specific content in content pages.

Nested Master Page


A nested master page allows you to create a hierarchy of master pages.
• Example: A site has a main master page for header/footer and a
nested master page for a specific section like Admin Panel.
• Content pages can then use the nested master page to inherit the
layout.

How to Create a Nested Master Page


Step 1: Create a Main Master Page ([Link])
<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="[Link]" Inherits="Site" %>

<!DOCTYPE html>
<html>
<head runat="server">
<title>My Site</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Site Header</h1>

21 | P a g e
<asp:ContentPlaceHolder ID="MainContent"
runat="server"></asp:ContentPlaceHolder>
<footer>Site Footer</footer>
</div>
</form>
</body>
</html>

Step 2: Create a Nested Master Page ([Link])


<%@ Master Language="C#" MasterPageFile="~/[Link]"
AutoEventWireup="true" CodeFile="[Link]" Inherits="Admin" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent"


runat="server">
<div>
<h2>Admin Panel</h2>
<asp:ContentPlaceHolder ID="AdminContent"
runat="server"></asp:ContentPlaceHolder>
</div>
</asp:Content>

Step 3: Create a Content Page Using Nested Master Page


<%@ Page Language="C#" MasterPageFile="~/[Link]"
AutoEventWireup="true" CodeFile="[Link]"
Inherits="Dashboard" %>

<asp:Content ID="Content1" ContentPlaceHolderID="AdminContent"


runat="server">
<p>Welcome to the Admin Dashboard!</p>
22 | P a g e
</asp:Content>

9. Explain DataAdapter object in detail.


→ DataAdapter Object in [Link]
The DataAdapter is a bridge between a DataSet and a data source (like
SQL Server).
• It fetches data from the database into a DataSet and updates
changes made in the DataSet back to the database.
• Works in Disconnected Mode Architecture.

Key Points about DataAdapter


1. Disconnected Architecture
o DataAdapter allows working with data without maintaining an
open connection.
o Data is fetched into a DataSet in memory.
2. Components of DataAdapter
o SelectCommand → Retrieves data from database.
o InsertCommand → Inserts new records into database.
o UpdateCommand → Updates existing records in database.
o DeleteCommand → Deletes records from database.
3. Fills DataSet
o The Fill() method is used to populate the DataSet with data.
4. Updates Database
o The Update() method is used to save changes made in the
DataSet back to the database.

Example in C#
23 | P a g e
using System;
using [Link];
using [Link];

class Program
{
static void Main()
{
string conStr = "Data Source=.;Initial Catalog=SchoolDB;Integrated
Security=True";
SqlConnection con = new SqlConnection(conStr);

// Create DataAdapter with SelectCommand


SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students",
con);

// Create DataSet
DataSet ds = new DataSet();

// Fill DataSet (disconnected)


[Link](ds, "Students");

// Display data
foreach (DataRow row in [Link]["Students"].Rows)
{
[Link]("ID: " + row["StudentID"] + ", Name: " +
row["Name"]);
}
24 | P a g e
// Modify DataSet locally
[Link]["Students"].Rows[0]["Name"] = "John Updated";

// Use SqlCommandBuilder to auto-generate update command


SqlCommandBuilder cb = new SqlCommandBuilder(da);

// Update database
[Link](ds, "Students");
}
}

10. Explain in brief the Menu controls and Calendar control


→ 1. Menu Control
Definition
The Menu control in [Link] is a navigation control used to create
hierarchical menus for websites.
• Supports multiple levels of menu items.
• Can be bound to SiteMap or created manually.
• Allows dynamic and static menus with expand/collapse features.
Features
• Supports horizontal or vertical orientation.
• Easy styling using CSS or properties.
• Can navigate to pages using NavigateUrl.
Example
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
<Items>
25 | P a g e
<asp:MenuItem Text="Home"
NavigateUrl="~/[Link]"></asp:MenuItem>
<asp:MenuItem Text="Products">
<asp:MenuItem Text="Electronics"
NavigateUrl="~/[Link]"></asp:MenuItem>
<asp:MenuItem Text="Clothing"
NavigateUrl="~/[Link]"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Contact"
NavigateUrl="~/[Link]"></asp:MenuItem>
</Items>
</asp:Menu>

2. Calendar Control
Definition
The Calendar control in [Link] allows users to select dates easily.
• Displays a monthly calendar view.
• Can be used to pick single or multiple dates.
Features
• Supports date selection events like SelectionChanged.
• Allows formatting, multiple months display, navigation between
months and years.
• Can restrict dates using TodaysDate, SelectionMode, etc.
Example
<asp:Calendar ID="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
<asp:Label ID="lblDate" runat="server" Text=""></asp:Label>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)

26 | P a g e
{
[Link] = "Selected Date: " +
[Link]();
}

11. List out state management techniques. Explain QueryString in detail


→ State Management Techniques in [Link]
In [Link], state management is used to maintain data across multiple
requests (since HTTP is stateless).
Types of State Management
1. Client-Side State Management
• Stores data on the user’s browser.
• Examples:
1. QueryString
2. Cookies
3. HiddenField
4. ViewState
2. Server-Side State Management
• Stores data on the web server.
• Examples:
1. Session State
2. Application State
3. Database (for persistent state)

QueryString in Detail
Definition

27 | P a g e
• The QueryString is a client-side state management technique that
passes data from one page to another using the URL.
• Data is appended to the URL after a ? symbol in name=value format.

Features of QueryString
1. Easy to use and requires no server memory.
2. Values are visible in the URL.
3. Can pass small amounts of data (not secure for sensitive
information).
4. Can be retrieved using [Link]["key"].

Example
[Link]
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Go"
OnClick="btnSubmit_Click" />
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = [Link];
[Link]("[Link]?user=" + name);
}
[Link]
<asp:Label ID="lblUser" runat="server"></asp:Label>
protected void Page_Load(object sender, EventArgs e)
{
if ([Link]["user"] != null)
{
[Link] = "Welcome, " + [Link]["user"];
28 | P a g e
}
}

12. Explain how to create and use web services.


→ Web Services in [Link]
Definition
• A Web Service is a software system designed to support
interoperable machine-to-machine communication over a
network.
• It allows applications written in different languages and platforms to
communicate using HTTP and XML (SOAP or REST).

Steps to Create and Use Web Services


1. Create a Web Service (ASMX)
1. Open Visual Studio → Create [Link] Web Application.
2. Add a Web Service: Right-click project → Add → New Item → Web
Service → Name it [Link].
3. Define Web Methods using [WebMethod] attribute.
Example: [Link]
using [Link];

[WebService(Namespace = "[Link]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : [Link]
{
[WebMethod]
public string SayHello(string name)
{
29 | P a g e
return "Hello, " + name;
}

[WebMethod]
public int AddNumbers(int a, int b)
{
return a + b;
}
}

2. Test the Web Service


• Run the project → Navigate to [Link] → You will see the list of
Web Methods.
• Click a method → Enter parameters → Click Invoke → See result.

3. Consume the Web Service in [Link]


Step 1: Add Web Reference
1. Right-click project → Add Service Reference → Advanced → Add Web
Reference.
2. Enter the URL of the Web Service
([Link] → Name it MyServiceRef.
Step 2: Call the Web Method in Code
using System;

public partial class WebServiceDemo : [Link]


{
protected void Page_Load(object sender, EventArgs e)
{
30 | P a g e
if (!IsPostBack)
{
[Link] service = new [Link]();
string greeting = [Link]("John");
[Link](greeting); // Output: Hello, John
}
}
}

13. What is a User Control? Explain creating and using a user control in
[Link].
→ What is a User Control
• A User Control is a custom, reusable control in [Link] that is
created by combining existing server controls and code.
• It has the file extension .ascx.
• User controls are used to avoid code duplication and maintain
consistent UI across multiple pages.
• Example: Header, Footer, Login Panel, Navigation Menu.

Creating a User Control


Step 1: Add a User Control
1. Right-click project → Add → New Item → Web User Control.
2. Name it [Link].
[Link]
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="[Link]" Inherits="Header" %>
<div style="background-color: lightblue; padding: 10px;">
31 | P a g e
<h1>My Website Header</h1>
<asp:Label ID="lblDate" runat="server"></asp:Label>
</div>
[Link]
protected void Page_Load(object sender, EventArgs e)
{
[Link] = "Today: " + [Link]();
}

Using a User Control


Step 1: Register User Control in a Page
• At the top of the page where you want to use it (e.g., [Link]), add:
<%@ Register TagPrefix="uc" TagName="Header" Src="~/[Link]" %>
Step 2: Add User Control in Page
<uc:Header ID="Header1" runat="server" />

14. Explain Login control with example.


→ Login Control in [Link]
Definition
• The Login control is a built-in [Link] server control used to
authenticate users.
• It provides a pre-built user interface for username and password
input.
• Can be used with Membership Provider to validate credentials.

Features
1. Built-in UI for username and password.

32 | P a g e
2. Supports authentication with Membership database or custom code.
3. Automatically provides failure messages on wrong login.
4. Supports PasswordRecovery, Remember Me, and redirect on
successful login.

Example of Login Control


Step 1: Add Login Control
<asp:Login ID="Login1" runat="server"
DestinationPageUrl="[Link]"
RememberMeSet="true" />
• DestinationPageUrl → Page to redirect after successful login.
• RememberMeSet → Option to remember login.

Step 2: Configure Authentication (Optional Custom Code)


If not using Membership, you can handle login in code-behind:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs
e)
{
string username = [Link];
string password = [Link];

// Example: simple hard-coded authentication


if (username == "admin" && password == "1234")
{
[Link] = true; // Login successful
}
else

33 | P a g e
{
[Link] = false; // Login failed
}
}
<asp:Login ID="Login1" runat="server"
OnAuthenticate="Login1_Authenticate" />

15. Consider table having following fields: Customer (c_id, name, city) Write
a code to perform insert, update and delete operation.
→ Table Structure
Customer
c_id INT PRIMARY KEY
name VARCHAR(50)
city VARCHAR(50)
[Link] Example (Using [Link] and SQL Server)
1. Connection String
string conStr = "Data Source=.;Initial Catalog=YourDatabase;Integrated
Security=True";
2. Insert Operation
using [Link];

void InsertCustomer(int id, string name, string city)


{
using (SqlConnection con = new SqlConnection(conStr))
{
string query = "INSERT INTO Customer (c_id, name, city) VALUES (@Id,
@Name, @City)";
SqlCommand cmd = new SqlCommand(query, con);
34 | P a g e
[Link]("@Id", id);
[Link]("@Name", name);
[Link]("@City", city);

[Link]();
[Link]();
[Link]();
}
}
3. Update Operation
void UpdateCustomer(int id, string name, string city)
{
using (SqlConnection con = new SqlConnection(conStr))
{
string query = "UPDATE Customer SET name=@Name, city=@City
WHERE c_id=@Id";
SqlCommand cmd = new SqlCommand(query, con);
[Link]("@Id", id);
[Link]("@Name", name);
[Link]("@City", city);

[Link]();
[Link]();
[Link]();
}
}
4. Delete Operation
35 | P a g e
void DeleteCustomer(int id)
{
using (SqlConnection con = new SqlConnection(conStr))
{
string query = "DELETE FROM Customer WHERE c_id=@Id";
SqlCommand cmd = new SqlCommand(query, con);
[Link]("@Id", id);

[Link]();
[Link]();
[Link]();
}
}
5. Example Usage in [Link] Page
protected void btnInsert_Click(object sender, EventArgs e)
{
InsertCustomer(1, "John", "Delhi");
}

protected void btnUpdate_Click(object sender, EventArgs e)


{
UpdateCustomer(1, "John Doe", "Mumbai");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
DeleteCustomer(1);
}
36 | P a g e
37 | P a g e

You might also like