Chapter 1
Advanced .NET Technology
TU BCA past exam questions
Past questions and answers
30 questions set from this chapter. Most repeated first.
- 2021 · 5 marks
Differentiate ASP.Net and .Net Core. Explain Net architecture in detail.
Answer
Difference between ASP.NET and .NET Core
| Basis | ASP.NET (.NET Framework) | .NET Core (ASP.NET Core) |
|---|---|---|
| Platform | Windows only | Cross-platform (Windows, Linux, macOS) |
| Hosting | IIS only | IIS, Kestrel, Nginx, Apache, Docker |
| Performance | Slower, heavier System.Web | Faster, modular, lightweight |
| Architecture | Web Forms, MVC, Web API separate | Unified MVC, Razor Pages, Web API |
| Deployment | Machine-wide framework install | Side-by-side, self-contained possible |
| Source | Partly closed | Open source |
| Configuration | web.config | appsettings.json, Program.cs |
| Dependency injection | Needs third-party container | Built in |
.NET architecture
The .NET Framework has these main parts:
- Operating system and hardware at the bottom, on which the framework runs.
- CLR (Common Language Runtime) is the execution engine. It provides memory management and garbage collection, the Common Type System (CTS), exception handling, thread management, code access security and JIT (Just-In-Time) compilation.
- Base Class Library (BCL / FCL) is the set of reusable classes, such as
System,System.IO,System.CollectionsandSystem.Data. - Application models are ASP.NET (web), Windows Forms/WPF (desktop), ADO.NET (data), WCF and others.
- Languages such as C#, VB.NET and F# follow the Common Language Specification (CLS), so they can interoperate.
Execution flow: source code (C#, VB.NET) is compiled by the language compiler into MSIL (Intermediate Language) plus metadata inside an assembly (.exe/.dll). At run time the CLR's JIT compiler converts the MSIL into native machine code, which then runs under CLR control (verification, garbage collection, security).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What are the two usages of interface? Write a program to achieve multiple inheritance in C#
Answer
Two usages of an interface
- Defining a contract (abstraction): an interface declares members (methods, properties, events) without implementation. Every implementing class must provide them, so unrelated classes can be used through a common type (polymorphism, loose coupling).
- Achieving multiple inheritance: C# does not allow a class to inherit from more than one class, but a class can implement any number of interfaces.
Program: multiple inheritance using interfaces
using System;
interface IShape
{
double Area();
}
interface IPrintable
{
void Print();
}
class Rectangle : IShape, IPrintable
{
double l, b;
public Rectangle(double l, double b) { this.l = l; this.b = b; }
public double Area() { return l * b; }
public void Print()
{
Console.WriteLine("Rectangle {0} x {1}, Area = {2}", l, b, Area());
}
}
class Program
{
static void Main()
{
Rectangle r = new Rectangle(5, 4);
r.Print();
IShape s = r; // use through the first interface
Console.WriteLine("Area via IShape = " + s.Area());
IPrintable p = r; // use through the second interface
p.Print();
}
}
Class Rectangle inherits behaviour from both IShape and IPrintable, which achieves multiple inheritance.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Differentiate throw and throws keyword. Write a program to copy contents of one file to another using binary reader and binary writer.
Answer
throw vs throws
C# has only the throw keyword. throws belongs to Java.
throw | throws (Java) |
|---|---|
| Used inside a method body to raise an exception object explicitly | Used in the method signature to declare which exceptions the method may pass to its caller |
Followed by an exception instance: throw new Exception("msg"); | Followed by exception class names |
| Throws one exception at a time | Can declare several exceptions, separated by commas |
| Exists in C# and Java | Not available in C# (C# has no checked exceptions) |
Program: copy a file using BinaryReader and BinaryWriter
using System;
using System.IO;
class FileCopy
{
static void Main()
{
try
{
using (BinaryReader br = new BinaryReader(File.Open("source.dat", FileMode.Open)))
using (BinaryWriter bw = new BinaryWriter(File.Open("dest.dat", FileMode.Create)))
{
byte[] buffer = new byte[1024];
int n;
while ((n = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, n);
}
}
Console.WriteLine("File copied successfully.");
}
catch (FileNotFoundException)
{
Console.WriteLine("Source file not found.");
}
catch (IOException e)
{
Console.WriteLine("IO error: " + e.Message);
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What are the benefits of win forms? Write common properties and events of different controls in win forms.
Answer
Benefits of Windows Forms
- Rapid application development (RAD) with the drag-and-drop designer in Visual Studio.
- A rich set of ready-made controls (Button, TextBox, DataGridView, etc.).
- Event-driven programming model that is easy to learn.
- Easy data binding to databases through ADO.NET.
- Rich, responsive native UI with access to local resources (files, printers).
- Controls can be inherited and customised (user controls). Forms support inheritance and reuse.
- Strong .NET class library support and easy deployment (ClickOnce).
Common properties and events of controls
| Control | Common properties | Common events |
|---|---|---|
| Form | Text, Name, BackColor, Size, StartPosition, WindowState, FormBorderStyle | Load, FormClosing, FormClosed, Resize, Click |
| Button | Text, Name, Enabled, Visible, BackColor, Font | Click, MouseEnter, MouseLeave |
| TextBox | Text, MaxLength, Multiline, PasswordChar, ReadOnly | TextChanged, KeyPress, KeyDown, Leave |
| Label | Text, Font, ForeColor, AutoSize | Click |
| CheckBox / RadioButton | Checked, Text, CheckState | CheckedChanged, CheckStateChanged |
| ComboBox / ListBox | Items, SelectedItem, SelectedIndex, DataSource | SelectedIndexChanged |
| DataGridView | DataSource, Columns, Rows, ReadOnly | CellClick, CellValueChanged |
| Timer | Interval, Enabled | Tick |
Properties common to almost all controls are Name, Text, Enabled, Visible, Location, Size, Font, BackColor and ForeColor.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What do you mean by tooltips? Explain different types of dialog box along with suitable programs.
Answer
Tooltip
A tooltip is a small pop-up text box that appears when the mouse pointer rests over a control. It gives a short hint about the control. In Windows Forms the ToolTip component is used: toolTip1.SetToolTip(button1, "Click to save");
Types of dialog box
A dialog box is a window used to interact with the user to get input or show information. There are two types.
- Modal dialog box: the user must close it before returning to the parent form. It is shown with
ShowDialog(). Examples are the common dialogs (OpenFileDialog,SaveFileDialog,ColorDialog,FontDialog) andMessageBox. - Modeless dialog box: the user can switch between the dialog and the parent form without closing it. It is shown with
Show(). An example is a Find and Replace window.
Examples
// Modal: message box and file dialog
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text files|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = System.IO.File.ReadAllText(ofd.FileName);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
DialogResult r = MessageBox.Show("Do you want to exit?", "Confirm",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (r == DialogResult.Yes) Application.Exit();
}
// Modeless: custom form
private void btnFind_Click(object sender, EventArgs e)
{
FindForm f = new FindForm();
f.Show(); // user can still use the main form
}
// Modal custom form
private void btnLogin_Click(object sender, EventArgs e)
{
LoginForm f = new LoginForm();
f.ShowDialog(); // main form blocked until closed
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What is ADO.Net? Differentiate dataset and data reader with suitable example.
Answer
ADO.NET
ADO.NET (ActiveX Data Objects .NET) is the .NET data access technology for connecting to a data source, executing commands and retrieving, manipulating and updating data. Its main classes are Connection, Command, DataReader, DataAdapter, DataSet and DataTable. It supports connected and disconnected data access.
DataSet vs DataReader
| DataSet | DataReader |
|---|---|
| Disconnected architecture | Connected architecture |
| Holds data in memory as tables, with relations and constraints | Reads rows directly from the database stream |
| Read/write; can insert, update and delete, then update the database through a DataAdapter | Read-only, forward-only |
| Can navigate forward and backward and hold multiple tables | Moves forward only, one row at a time |
| Uses more memory, slower for big data | Faster, uses less memory |
| Connection can be closed after filling | Connection must stay open while reading |
Example
string cs = "Data Source=.;Initial Catalog=College;Integrated Security=True";
// DataReader
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from Student", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
Console.WriteLine(dr["Name"]);
}
// DataSet
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("select * from Student", con);
DataSet ds = new DataSet();
da.Fill(ds, "Student"); // connection opened and closed automatically
foreach (DataRow row in ds.Tables["Student"].Rows)
Console.WriteLine(row["Name"]);
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What is GDI+? Write a program to draw line and circle in win form.
Answer
GDI+
GDI+ (Graphics Device Interface Plus) is the .NET graphics API in the System.Drawing namespace. It is used to draw 2D graphics, text and images on the screen or printer through a Graphics object, using Pen, Brush, Font and Color. It can draw lines, rectangles, ellipses, curves, polygons and images.
Program: draw a line and a circle in a Windows Form
using System;
using System.Drawing;
using System.Windows.Forms;
public class DrawForm : Form
{
public DrawForm()
{
this.Text = "GDI+ Demo";
this.Size = new Size(400, 350);
this.Paint += new PaintEventHandler(DrawForm_Paint);
}
private void DrawForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Blue, 3);
// line from (30,50) to (300,50)
g.DrawLine(pen, 30, 50, 300, 50);
// circle: ellipse with equal width and height (diameter 100)
g.DrawEllipse(Pens.Red, 100, 100, 100, 100);
// filled circle
g.FillEllipse(Brushes.Green, 100, 220, 80, 80);
pen.Dispose();
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new DrawForm());
}
}
DrawEllipse with equal width and height produces a circle.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
a) Explain two architectures of ADO.Net.
b) Write a C# program to demonstrate transaction using ADO.Net.
Answer
(a) Two architectures of ADO.NET
1. Connected architecture
The application keeps an open connection to the database while it works. It uses SqlConnection, SqlCommand and SqlDataReader.
- The data reader is forward-only and read-only.
- It is fast and uses little memory.
- It needs a continuous connection, so it is not scalable for many users.
- It is suitable for reading large amounts of data once.
2. Disconnected architecture
Data is fetched using a SqlDataAdapter, stored in a DataSet/DataTable in memory, and the connection is closed. The user works on the in-memory copy and the changes are sent back with adapter.Update().
- It is scalable, since the connection is held briefly.
- It supports multiple tables, relations, sorting and filtering, and the data can be serialised to XML.
- It uses more memory and the data may be stale or cause concurrency conflicts.
(b) Transaction using ADO.NET
using System;
using System.Data.SqlClient;
class TransactionDemo
{
static void Main()
{
string cs = "Data Source=.;Initial Catalog=Bank;Integrated Security=True";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlTransaction tran = con.BeginTransaction();
try
{
SqlCommand c1 = new SqlCommand(
"update Account set Balance = Balance - 500 where AccNo = 1", con, tran);
c1.ExecuteNonQuery();
SqlCommand c2 = new SqlCommand(
"update Account set Balance = Balance + 500 where AccNo = 2", con, tran);
c2.ExecuteNonQuery();
tran.Commit(); // both succeed
Console.WriteLine("Transaction committed.");
}
catch (Exception ex)
{
tran.Rollback(); // undo everything on failure
Console.WriteLine("Rolled back: " + ex.Message);
}
}
}
}
Either both updates are applied (commit) or none (rollback), which preserves atomicity.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
a) Explain docker and containerization with suitable example.
b) Develop a win form application to show complete CRUD operation of employee.
Answer
(a) Docker and containerization
Containerization packages an application with all its dependencies (runtime, libraries, configuration) into a lightweight, isolated unit called a container. Containers share the host OS kernel, so they start in seconds and use fewer resources than virtual machines. They run the same way on a developer's laptop, a test server and the cloud.
Docker is the most popular containerization platform. Its key concepts:
- Dockerfile: a text file with instructions to build an image.
- Image: a read-only template containing the app and its dependencies.
- Container: a running instance of an image.
- Docker Hub / registry: a place to store and share images.
- Docker Engine: the daemon that builds and runs containers.
Example: containerizing an ASP.NET Core app
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /out
FROM base AS final
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApp.dll"]
docker build -t myapp .
docker run -d -p 8080:80 myapp
(b) Windows Forms CRUD for Employee
Assume the table Employee(Id int primary key, Name varchar(50), Address varchar(50), Salary decimal). The form has TextBoxes txtId, txtName, txtAddress, txtSalary, buttons btnInsert, btnUpdate, btnDelete, btnView and a DataGridView dgv.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public partial class EmployeeForm : Form
{
string cs = "Data Source=.;Initial Catalog=Company;Integrated Security=True";
public EmployeeForm() { InitializeComponent(); }
private void Load_Data()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("select * from Employee", con);
DataTable dt = new DataTable();
da.Fill(dt);
dgv.DataSource = dt;
}
}
private void Execute(string sql)
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@id", int.Parse(txtId.Text));
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@addr", txtAddress.Text);
cmd.Parameters.AddWithValue("@sal", decimal.Parse(txtSalary.Text));
con.Open();
cmd.ExecuteNonQuery();
}
Load_Data();
}
private void btnInsert_Click(object s, EventArgs e) =>
Execute("insert into Employee values(@id,@name,@addr,@sal)");
private void btnUpdate_Click(object s, EventArgs e) =>
Execute("update Employee set Name=@name, Address=@addr, Salary=@sal where Id=@id");
private void btnDelete_Click(object s, EventArgs e) =>
Execute("delete from Employee where Id=@id");
private void btnView_Click(object s, EventArgs e) => Load_Data();
private void dgv_CellClick(object s, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
DataGridViewRow r = dgv.Rows[e.RowIndex];
txtId.Text = r.Cells[0].Value.ToString();
txtName.Text = r.Cells[1].Value.ToString();
txtAddress.Text = r.Cells[2].Value.ToString();
txtSalary.Text = r.Cells[3].Value.ToString();
}
}
Create is the insert, Read is the view, Update is the update and Delete is the delete.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
a) Write a C# program to demonstrate multithreading. You must use sleep() method in your program.
b) Write a C# program to calculate factorial of a number in win form as follows:
Answer
(a) Multithreading with Sleep()
using System;
using System.Threading;
class ThreadDemo
{
static void PrintNumbers()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Numbers thread: " + i);
Thread.Sleep(500); // pause for 500 ms
}
}
static void PrintLetters()
{
for (char c = 'A'; c <= 'E'; c++)
{
Console.WriteLine("Letters thread: " + c);
Thread.Sleep(700);
}
}
static void Main()
{
Thread t1 = new Thread(PrintNumbers);
Thread t2 = new Thread(PrintLetters);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine("Main thread finished.");
}
}
The two threads run concurrently, and Sleep() suspends the current thread for the given milliseconds so the output interleaves.
(b) Factorial in a Windows Form
Assumed form layout: txtNumber (TextBox), btnCalculate (Button) and lblResult (Label).
using System;
using System.Windows.Forms;
public partial class FactorialForm : Form
{
public FactorialForm() { InitializeComponent(); }
private void btnCalculate_Click(object sender, EventArgs e)
{
int n;
if (!int.TryParse(txtNumber.Text, out n) || n < 0)
{
MessageBox.Show("Enter a non-negative integer.");
return;
}
long fact = 1;
for (int i = 2; i <= n; i++)
fact *= i;
lblResult.Text = "Factorial of " + n + " = " + fact;
}
}
For example, entering 5 shows Factorial of 5 = 120. A long holds values only up to 20!.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Explain thread lifecycle. Write a multithreaded program using C#.
Answer
Thread lifecycle
A thread in .NET (System.Threading.Thread) passes through these states (ThreadState):
- Unstarted: the thread object has been created (
new Thread(...)) butStart()has not been called. - Runnable / Running: after
Start()the thread is ready and is scheduled by the OS to run on the CPU. - Waiting / Blocked (WaitSleepJoin): the thread is paused by
Sleep(),Join(),Wait()or a lock/IO wait. It returns to runnable when the condition ends. - Suspended / Aborted-requested: the thread has been asked to stop (
Abort, now deprecated) or cancelled. - Stopped (Dead): the thread has finished its method or been terminated. It cannot be restarted.
Unstarted --Start()--> Running <--> WaitSleepJoin
|
(finish / Abort)
v
Stopped
Multithreaded program
using System;
using System.Threading;
class Program
{
static void Worker(string name)
{
for (int i = 1; i <= 3; i++)
{
Console.WriteLine(name + " : step " + i);
Thread.Sleep(300);
}
}
static void Main()
{
Thread t1 = new Thread(() => Worker("Thread-1"));
Thread t2 = new Thread(() => Worker("Thread-2"));
Console.WriteLine("t1 state: " + t1.ThreadState); // Unstarted
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine("t1 state: " + t1.ThreadState); // Stopped
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is MDI form? Explain different types of dialog boxes with suitable examples.
Answer
MDI form
A Multiple Document Interface (MDI) application has one parent window that can host several child windows inside it (for example Word with several documents, or a text editor with several files). Set the parent's IsMdiContainer = true and set each child's MdiParent:
Form2 child = new Form2();
child.MdiParent = this;
child.Show();
this.LayoutMdi(MdiLayout.Cascade); // also TileHorizontal, TileVertical, ArrangeIcons
Types of dialog boxes
- Modal dialog box: the user must close it before returning to the owner form. It is shown with
ShowDialog(). Examples areMessageBox,OpenFileDialog,SaveFileDialog,ColorDialog,FontDialogand a custom login form. - Modeless dialog box: the owner form stays accessible while the dialog is open. It is shown with
Show(). An example is a Find/Replace box.
// Modal
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
this.BackColor = cd.Color;
MessageBox.Show("Saved successfully", "Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
// Modeless
FindDialog f = new FindDialog();
f.Owner = this;
f.Show();
DialogResult (OK, Cancel, Yes, No) returns which button the user pressed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Differentiate connected and disconnected ADO.Net architecture with suitable example.
Answer
Connected vs disconnected ADO.NET architecture
| Connected | Disconnected |
|---|---|
| Connection stays open during data access | Connection is opened only to fill or update the data |
Uses Connection, Command, DataReader | Uses DataAdapter, DataSet/DataTable |
| Forward-only, read-only | Read/write, can navigate both ways |
| Fast, low memory | Uses more memory (data cached) |
| Poor scalability, as connections are held | Scalable for many users |
| Always shows live data | Data may become stale; conflicts must be handled |
| One table at a time | Multiple tables with relations |
Example: connected
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select Name from Student", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
Console.WriteLine(dr[0]);
con.Close();
Example: disconnected
SqlDataAdapter da = new SqlDataAdapter("select * from Student", cs);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "Student"); // connection closed after filling
ds.Tables["Student"].Rows[0]["Name"] = "Hari"; // edit in memory
da.Update(ds, "Student"); // push changes to the database
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define virtual directory in IIS. Develop ASP.Net web form application to create and access session.
Answer
Virtual directory in IIS
A virtual directory is a name (alias) in IIS that maps to a physical folder on disk, which may be anywhere on the server or on another computer. For example, the URL http://localhost/MyApp can point to D:\Projects\MyApp. It lets a site publish content from outside its root folder and hides the real file path from users. It is created in IIS Manager with right-click on the site, then Add Virtual Directory, giving an alias and a physical path.
ASP.NET web form: create and access a session
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<body>
<form id="form1" runat="server">
Name: <asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="btnCreate" runat="server" Text="Create Session" OnClick="btnCreate_Click" />
<asp:Button ID="btnAccess" runat="server" Text="Access Session" OnClick="btnAccess_Click" />
<br />
<asp:Label ID="lblMsg" runat="server" />
</form>
</body>
</html>
Default.aspx.cs
using System;
public partial class _Default : System.Web.UI.Page
{
protected void btnCreate_Click(object sender, EventArgs e)
{
Session["UserName"] = txtName.Text; // create session variable
Session.Timeout = 20; // minutes
lblMsg.Text = "Session created.";
}
protected void btnAccess_Click(object sender, EventArgs e)
{
if (Session["UserName"] != null)
lblMsg.Text = "Hello, " + Session["UserName"].ToString();
else
lblMsg.Text = "No session found.";
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Explain MVC using ASP.Net core with suitable example.
Answer
MVC in ASP.NET Core
MVC (Model-View-Controller) separates an application into three parts:
- Model: the data and business logic (classes, validation, database access).
- View: the UI, written in Razor (
.cshtml), which displays model data. - Controller: it handles the HTTP request, works with the model and returns a view.
Request flow: URL, then routing, then the controller action, then the model, then the view, then the HTML response to the browser.
Benefits are separation of concerns, easy unit testing, parallel development and clean URLs.
Example
Model Models/Student.cs
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller Controllers/StudentController.cs
using Microsoft.AspNetCore.Mvc;
public class StudentController : Controller
{
public IActionResult Index()
{
var student = new Student { Id = 1, Name = "Sita" };
return View(student); // passes the model to Views/Student/Index.cshtml
}
}
View Views/Student/Index.cshtml
@model Student
<h2>Student Details</h2>
<p>Id: @Model.Id</p>
<p>Name: @Model.Name</p>
Routing in Program.cs:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
Visiting /Student/Index runs the action and renders the view.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define AJAX. Explain ASP.Net AJAX server control with suitable example.
Answer
AJAX
AJAX (Asynchronous JavaScript and XML) is a technique for sending requests to the server and updating part of a web page in the background without reloading the whole page. It gives faster, smoother, more interactive pages. It uses JavaScript, XMLHttpRequest/fetch, the DOM and XML/JSON.
ASP.NET AJAX server controls
- ScriptManager: manages the AJAX client scripts. One is required on each page that uses AJAX.
- UpdatePanel: defines the region of the page that is refreshed partially (asynchronous postback). It has
ContentTemplateandTriggers. - UpdateProgress: shows a status message (e.g. "Loading...") while an UpdatePanel is updating.
- Timer: triggers postbacks at fixed intervals.
- ScriptManagerProxy: used in content or user control pages when a master page already holds a ScriptManager.
Example
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" />
<asp:Button ID="btnTime" runat="server" Text="Show Time" OnClick="btnTime_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>Please wait...</ProgressTemplate>
</asp:UpdateProgress>
protected void btnTime_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
lblTime.Text = DateTime.Now.ToString();
}
Only the label and button update, and the rest of the page does not reload.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What do you mean by hosting models? Explain docker and containerization in detail.
Answer
Hosting models
A hosting model describes how an ASP.NET Core application runs on a server.
- In-process hosting: the app runs inside the IIS worker process (
w3wp.exe) using the IIS HTTP Server. It has better performance and is the default for IIS. - Out-of-process hosting: the app runs as a separate process on the Kestrel web server. IIS, Nginx or Apache act as a reverse proxy and forward requests to Kestrel. It is used on Linux and when running Kestrel directly.
- Self-hosting / containers: Kestrel runs as a console app, in a Windows Service or in a Docker container, and cloud hosting (Azure, AWS) is also possible.
Docker and containerization
Containerization packages an application with its runtime, libraries and configuration into an isolated container. Containers share the host OS kernel, so they are lighter and faster than virtual machines. The result is the same behaviour in development, testing and production.
Docker is the platform to build, ship and run containers.
- Dockerfile gives the build instructions.
- Image is a read-only template built from a Dockerfile.
- Container is a running instance of an image.
- Registry (Docker Hub) stores images.
- Docker Engine is the daemon that runs containers.
Advantages: portability, isolation, consistency across environments, fast start-up, efficient resource use, easy scaling and CI/CD integration.
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /out
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /out .
EXPOSE 80
ENTRYPOINT ["dotnet", "WebApp.dll"]
docker build -t webapp .
docker run -d -p 8080:80 webapp
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Create a ASP.Net web form for employee registration containing input fields for employee id, name, address, gender, department and two buttons for inserting and selecting data. You should insert data to a database table on insert button clicked and on select button clicked select and display employee data in DataGrid whose address is 'Ktm' and department is 'IT'.
Answer
Assume the table:
CREATE TABLE Employee(
EmpId int PRIMARY KEY,
Name varchar(50),
Address varchar(50),
Gender varchar(10),
Department varchar(30)
);
EmployeeForm.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmployeeForm.aspx.cs" Inherits="EmployeeForm" %>
<html>
<body>
<form id="form1" runat="server">
<table>
<tr><td>Employee Id</td><td><asp:TextBox ID="txtId" runat="server" /></td></tr>
<tr><td>Name</td><td><asp:TextBox ID="txtName" runat="server" /></td></tr>
<tr><td>Address</td><td><asp:TextBox ID="txtAddress" runat="server" /></td></tr>
<tr><td>Gender</td><td>
<asp:RadioButtonList ID="rblGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList></td></tr>
<tr><td>Department</td><td>
<asp:DropDownList ID="ddlDept" runat="server">
<asp:ListItem>IT</asp:ListItem>
<asp:ListItem>HR</asp:ListItem>
<asp:ListItem>Finance</asp:ListItem>
</asp:DropDownList></td></tr>
</table>
<asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
<asp:Button ID="btnSelect" runat="server" Text="Select" OnClick="btnSelect_Click" />
<br /><asp:Label ID="lblMsg" runat="server" />
<asp:GridView ID="gvEmployee" runat="server" />
</form>
</body>
</html>
EmployeeForm.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
public partial class EmployeeForm : System.Web.UI.Page
{
string cs = "Data Source=.;Initial Catalog=Company;Integrated Security=True";
protected void btnInsert_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(
"insert into Employee values(@id,@name,@addr,@gender,@dept)", con);
cmd.Parameters.AddWithValue("@id", int.Parse(txtId.Text));
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@addr", txtAddress.Text);
cmd.Parameters.AddWithValue("@gender", rblGender.SelectedValue);
cmd.Parameters.AddWithValue("@dept", ddlDept.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Employee inserted successfully.";
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter(
"select * from Employee where Address=@addr and Department=@dept", con);
da.SelectCommand.Parameters.AddWithValue("@addr", "Ktm");
da.SelectCommand.Parameters.AddWithValue("@dept", "IT");
DataTable dt = new DataTable();
da.Fill(dt);
gvEmployee.DataSource = dt;
gvEmployee.DataBind();
}
}
}
The Select button runs a parameterised query for address Ktm and department IT and binds the result to the grid. The classic DataGrid and GridView bind in the same way.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
a) Write a C# program to demonstrate typed dataset.
b) Write a C# program to copy contents of one file to another using binary reader and writer.
Answer
(a) Typed dataset
A typed DataSet is a class generated (in Visual Studio, by adding a DataSet .xsd item) that derives from DataSet and exposes tables, rows and columns as strongly typed properties. It gives compile-time checking and IntelliSense. For example, ds.Student[0].Name is used in place of ds.Tables["Student"].Rows[0]["Name"].
Assume a typed dataset StudentDS with the table Student (Id, Name, Address), generated from the database.
using System;
class TypedDataSetDemo
{
static void Main()
{
StudentDS ds = new StudentDS();
// add rows using strongly typed methods
ds.Student.AddStudentRow(1, "Ram", "Kathmandu");
ds.Student.AddStudentRow(2, "Sita", "Pokhara");
// read with typed properties (no casting, no string column names)
foreach (StudentDS.StudentRow row in ds.Student)
{
Console.WriteLine("{0} {1} {2}", row.Id, row.Name, row.Address);
}
// find and edit
StudentDS.StudentRow r = ds.Student.FindById(2);
r.Address = "Lalitpur";
Console.WriteLine(ds.Student[1].Address);
}
}
(b) Copy a file using BinaryReader and BinaryWriter
using System;
using System.IO;
class CopyFile
{
static void Main()
{
using (BinaryReader br = new BinaryReader(new FileStream("a.dat", FileMode.Open)))
using (BinaryWriter bw = new BinaryWriter(new FileStream("b.dat", FileMode.Create)))
{
byte[] buf = new byte[4096];
int n;
while ((n = br.Read(buf, 0, buf.Length)) > 0)
bw.Write(buf, 0, n);
}
Console.WriteLine("Copied.");
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Differentiate ASP.Net and ASP.Net core. Create ASP.Net core application containing razor page, model and controller to calculate simple interest.
Answer
ASP.NET vs ASP.NET Core
| ASP.NET | ASP.NET Core |
|---|---|
| Runs on the .NET Framework, Windows only | Runs on .NET (Core), cross-platform |
| Hosted on IIS | IIS, Kestrel, Nginx, Apache, Docker |
| Slower, depends on System.Web | Faster and modular (NuGet packages) |
| Web Forms, MVC and Web API are separate | MVC, Razor Pages and Web API are unified |
Configuration in web.config | appsettings.json, environment variables |
| Dependency injection needs third-party tools | Built-in DI |
| Not open source in full | Open source |
Simple interest application (Razor Page, model and controller)
Model Models/InterestModel.cs
using System.ComponentModel.DataAnnotations;
public class InterestModel
{
[Required] public double Principal { get; set; }
[Required] public double Rate { get; set; }
[Required] public double Time { get; set; }
public double? SimpleInterest { get; set; }
}
Controller Controllers/InterestController.cs
using Microsoft.AspNetCore.Mvc;
public class InterestController : Controller
{
[HttpGet]
public IActionResult Index() => View(new InterestModel());
[HttpPost]
public IActionResult Index(InterestModel m)
{
if (ModelState.IsValid)
m.SimpleInterest = (m.Principal * m.Rate * m.Time) / 100;
return View(m);
}
}
Razor view Views/Interest/Index.cshtml
@model InterestModel
<h2>Simple Interest Calculator</h2>
<form asp-action="Index" method="post">
<div>Principal (Rs): <input asp-for="Principal" /></div>
<div>Rate (%): <input asp-for="Rate" /></div>
<div>Time (years): <input asp-for="Time" /></div>
<button type="submit">Calculate</button>
</form>
@if (Model.SimpleInterest != null)
{
<p>Simple Interest = Rs @Model.SimpleInterest</p>
}
The calculation uses
For example, , , gives , so the interest is Rs 1000.
Program.cs needs builder.Services.AddControllersWithViews(); and app.MapControllerRoute(name: "default", pattern: "{controller=Interest}/{action=Index}/{id?}");.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is thread? Write a C# program to create multiple thread along with main Thread.
Answer
Thread
A thread is the smallest unit of execution within a process. A process can have many threads that share its memory and resources but run independently. Multithreading allows several tasks to run concurrently, improving responsiveness and CPU use. In C# threads are created with System.Threading.Thread.
Program: multiple threads along with the main thread
using System;
using System.Threading;
class Program
{
static void Task1()
{
for (int i = 1; i <= 4; i++)
{
Console.WriteLine("Thread 1: " + i);
Thread.Sleep(400);
}
}
static void Task2()
{
for (int i = 1; i <= 4; i++)
{
Console.WriteLine("Thread 2: " + i);
Thread.Sleep(600);
}
}
static void Main()
{
Thread.CurrentThread.Name = "Main";
Thread t1 = new Thread(new ThreadStart(Task1));
Thread t2 = new Thread(new ThreadStart(Task2));
t1.Start();
t2.Start();
for (int i = 1; i <= 4; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + " thread: " + i);
Thread.Sleep(500);
}
t1.Join();
t2.Join();
Console.WriteLine("All threads completed.");
}
}
The main thread and the two worker threads run concurrently, so their output is interleaved.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is difference between SDI and MDI application? How form inheritance can be performed in windows application?
Answer
SDI vs MDI
| SDI (Single Document Interface) | MDI (Multiple Document Interface) |
|---|---|
| Each window holds one document and is independent | One parent window contains many child windows |
| Several documents mean several separate windows | Child windows live inside the parent and cannot leave it |
| Example: Notepad, MS Paint | Example: older MS Word/Excel, Visual Studio |
| Simple to build; more memory per instance | More complex; shares the menu and toolbar of the parent |
No IsMdiContainer needed | Parent has IsMdiContainer = true, children set MdiParent |
Form inheritance in Windows applications
Visual (form) inheritance lets a new form derive from an existing form and inherit its controls, properties and code. This promotes reuse (for example a common base form with logo, header and Save/Cancel buttons).
Steps:
- Create the base form
BaseForm, build the project, and set controls the children may change toProtectedorPublic(Modifiers property). - Add a new item, Inherited Form, and choose
BaseFormas the base, or write the class manually:
public class BaseForm : Form
{
protected Button btnClose = new Button();
public BaseForm() { btnClose.Text = "Close"; btnClose.Click += (s, e) => Close(); Controls.Add(btnClose); }
}
public class StudentForm : BaseForm // inherits controls and behaviour
{
public StudentForm() { Text = "Student"; }
}
The derived form shows all base controls and can add new ones or override behaviour.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is disconnected architecture in ADO.NET? How ADO.NET differs from classical ADO?
Answer
Disconnected architecture in ADO.NET
In the disconnected architecture the application connects to the database only to fetch or save data. A DataAdapter fills a DataSet/DataTable, the connection closes, and the application works on the in-memory copy. Changes are later sent back with DataAdapter.Update().
SqlDataAdapter da = new SqlDataAdapter("select * from Student", cs);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "Student");
ds.Tables["Student"].Rows[0]["Name"] = "Gita";
da.Update(ds, "Student");
Advantages are scalability, fewer connections, support for multiple tables and relations, and XML support. Disadvantages are higher memory use and possible stale data or update conflicts.
ADO.NET vs classic ADO
| Classic ADO | ADO.NET |
|---|---|
| Mostly connected, uses Recordset | Both connected and disconnected (DataReader, DataSet) |
| One table-like Recordset; joins needed | DataSet holds multiple tables and relations |
| COM based; data types marshalled | Managed code, no COM marshalling |
| Data transferred as binary | Data transferred as XML, firewall friendly |
| Limited scalability | Designed for scalable, web applications |
| Weak support for XML | Strong XML integration |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is difference between HTML server control and Web server control? Explain with example.
Answer
HTML server controls vs Web server controls
| HTML server control | Web server control |
|---|---|
Ordinary HTML elements made server-accessible by runat="server" | ASP.NET controls with the asp: prefix |
Namespace System.Web.UI.HtmlControls | Namespace System.Web.UI.WebControls |
| Maps one-to-one to HTML tags and attributes | Abstract, rich objects that render suitable HTML for each browser |
| Few properties, mostly HTML attributes | Rich object model (styles, templates, data binding) |
Event model is limited (onserverclick) | Full event model (OnClick, OnTextChanged) |
| Used to convert existing HTML pages | Used for new ASP.NET development |
Examples: HtmlInputText, HtmlButton | Examples: TextBox, Button, GridView |
Example
<!-- HTML server control -->
<input type="text" id="txtHtml" runat="server" />
<input type="button" id="btnHtml" value="HTML Button" runat="server" onserverclick="btnHtml_Click" />
<!-- Web server control -->
<asp:TextBox ID="txtWeb" runat="server" />
<asp:Button ID="btnWeb" runat="server" Text="Web Button" OnClick="btnWeb_Click" />
protected void btnHtml_Click(object sender, EventArgs e) { txtHtml.Value = "Hello HTML"; }
protected void btnWeb_Click(object sender, EventArgs e) { txtWeb.Text = "Hello Web"; }
An HTML control uses .Value while a web control uses .Text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is authentication? Briefly explain form authentication in ASP.NET.
Answer
Authentication
Authentication is the process of verifying the identity of a user, normally by credentials such as a user name and password. It answers "who are you?" and is different from authorization, which decides what the user may access. ASP.NET supports Windows, Forms and Passport/Token authentication.
Forms authentication
Forms authentication lets the application show its own login page and keep the user's identity in an encrypted cookie (authentication ticket).
Working:
- The user requests a protected page.
- ASP.NET sees no valid ticket and redirects to the login page.
- The user submits credentials and the app validates them (for example against a database).
- On success,
FormsAuthentication.RedirectFromLoginPage(userName, persist)issues the cookie and sends the user to the originally requested page. - Later requests carry the cookie, so no new login is needed.
FormsAuthentication.SignOut()removes the cookie.
web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="30" />
</authentication>
<authorization>
<deny users="?" /> <!-- deny anonymous users -->
</authorization>
</system.web>
Login.aspx.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUser.Text == "admin" && txtPass.Text == "1234") // normally checked in the database
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, false);
else
lblMsg.Text = "Invalid username or password";
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Explain different controls of ASP.NET AJAX.
Answer
Controls of ASP.NET AJAX
ASP.NET AJAX provides server controls that add asynchronous behaviour without writing JavaScript.
- ScriptManager: the core control. It manages the AJAX scripts, enables partial-page rendering and must appear once on a page before other AJAX controls.
- UpdatePanel: marks a region that is refreshed through asynchronous postbacks, so only that region changes.
ContentTemplateholds the controls, andTriggers(AsyncPostBackTrigger,PostBackTrigger) define what causes the update.UpdateModecan be Always or Conditional. - UpdateProgress: shows a progress message or animation while an UpdatePanel is being updated (
AssociatedUpdatePanelID,ProgressTemplate,DisplayAfter). - Timer: raises postbacks at a set interval (
Intervalin ms,Tickevent). It is used for auto-refresh, for example a clock or news ticker. - ScriptManagerProxy: lets content pages or user controls register scripts or services when the ScriptManager is already on the master page.
- AJAX Control Toolkit controls: extenders such as
AutoCompleteExtender,CalendarExtender,ModalPopupExtender,Accordion,TabContainerandConfirmButtonExtender.
<asp:ScriptManager ID="sm" runat="server" />
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" />
<asp:UpdatePanel ID="up" runat="server">
<ContentTemplate><asp:Label ID="lblClock" runat="server" /></ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /></Triggers>
</asp:UpdatePanel>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is kestrel? How it differ from IIS?
Answer
Kestrel
Kestrel is the cross-platform, lightweight, high-performance web server built into ASP.NET Core. It is based on libuv/sockets, handles HTTP requests directly and is the default server for every ASP.NET Core application. It can run on its own (edge server) or behind a reverse proxy such as IIS, Nginx or Apache, which adds security, load balancing, SSL and static-file features.
Kestrel vs IIS
| Kestrel | IIS |
|---|---|
| Cross-platform (Windows, Linux, macOS) | Windows only |
| Part of ASP.NET Core, runs inside the app process | A full web server product in Windows, runs w3wp.exe |
| Fast and minimal features | Rich features: management console, authentication, logging, request filtering, load balancing |
| Hosts only ASP.NET Core | Hosts ASP.NET, ASP.NET Core, PHP and static sites |
| Normally put behind a reverse proxy in production | Can face the internet directly and act as a reverse proxy |
Configured in code/appsettings.json | Configured through IIS Manager/web.config |
Supports process-level launch (dotnet run) | Supports in-process and out-of-process hosting of ASP.NET Core |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
Differentiate between class and interface? Why do we need serialization in file handling in C#? Write a C# program to save Student record (roll, name, address, and phone number) into file "student.txt" and then display student record.
Answer
Class vs interface
| Class | Interface |
|---|---|
| Can contain fields, constructors, and implemented methods | Declares members only (default implementations are possible in newer C#) |
| Can be instantiated | Cannot be instantiated |
| Supports single inheritance only | A class can implement multiple interfaces |
| Members can have access modifiers | Members are public by default |
| Defines what an object is and how it works | Defines a contract, what an object can do |
Keyword class | Keyword interface |
Need for serialization
Serialization converts an object (its state) into a stream of bytes or text (binary, XML, JSON) so that it can be:
- saved to a file or database and restored later (persistence),
- sent across a network or between applications (remoting, web services),
- copied (deep clone) or kept in session state.
Deserialization rebuilds the object from the stream. Without it, each field would have to be written and read manually.
Program: save student records to student.txt and display them
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
[Serializable]
public class Student
{
public int Roll { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
class Program
{
static void Main()
{
List<Student> list = new List<Student>();
Console.Write("How many students? ");
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
Student s = new Student();
Console.Write("Roll: "); s.Roll = int.Parse(Console.ReadLine());
Console.Write("Name: "); s.Name = Console.ReadLine();
Console.Write("Address: "); s.Address = Console.ReadLine();
Console.Write("Phone: "); s.Phone = Console.ReadLine();
list.Add(s);
}
// serialize to file
File.WriteAllText("student.txt", JsonSerializer.Serialize(list));
// deserialize and display
string json = File.ReadAllText("student.txt");
List<Student> saved = JsonSerializer.Deserialize<List<Student>>(json);
Console.WriteLine("\nRoll\tName\tAddress\tPhone");
foreach (Student s in saved)
Console.WriteLine("{0}\t{1}\t{2}\t{3}", s.Roll, s.Name, s.Address, s.Phone);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
What are advantages of ASP.NET MVC? Explain different state management techniques in ASP.NET.
Answer
Advantages of ASP.NET MVC
- Separation of concerns: Model, View and Controller are independent, so code is easier to maintain.
- Testability: controllers and models can be unit tested without the UI.
- Full control over HTML and no ViewState or server-control lifecycle, which gives lighter pages.
- Clean, SEO-friendly URLs through routing (
/Product/Details/5). - Parallel development by UI, logic and data teams.
- Supports TDD, dependency injection, Razor views, filters, and works well with JavaScript frameworks and Web API.
- Extensible and scalable.
State management techniques in ASP.NET
HTTP is stateless, so state is kept by the following techniques.
Client-side:
- ViewState: page and control values stored in a hidden field (
ViewState["k"] = v), valid only for the same page. - Hidden fields: values in
<input type="hidden">. - Cookies: small text data in the browser (
Response.Cookies["name"].Value = "x"), which can persist across sessions. - Query string: data in the URL (
page.aspx?id=5), visible and limited in size. - Control state: a protected form of ViewState for essential control data.
Server-side:
- Session state: per-user data on the server (
Session["user"] = "Ram"), with a timeout, kept in-proc, State Server or SQL Server. - Application state: global data shared by all users (
Application["count"]). - Cache: data stored on the server for reuse, with expiry.
- TempData / ViewBag / ViewData (MVC): pass data between controller and view. TempData survives a redirect.
- Database: persistent storage for important data.
Client-side methods reduce server load but are less secure. Server-side methods are more secure but use server memory.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
What is validation control in web development? Explain various control for validation in ASP.NET with suitable program.
Answer
Validation control
A validation control checks the data a user enters in an input control before it is processed, so wrong or missing values are caught on the client (JavaScript) and again on the server. This keeps data accurate and the application secure. Each validator is attached to an input control by ControlToValidate and shows an ErrorMessage.
Validation controls in ASP.NET
- RequiredFieldValidator: the field must not be empty.
- CompareValidator: compares a value with another control or a constant (
Operator,Type), for example password confirmation. - RangeValidator: value must lie between
MinimumValueandMaximumValue. - RegularExpressionValidator: value must match a pattern (email, phone).
- CustomValidator: user-defined client or server logic.
- ValidationSummary: displays all validation errors in one place.
Program
<form id="form1" runat="server">
Name: <asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtName"
ErrorMessage="Name is required" ForeColor="Red" Display="Dynamic" /><br />
Age: <asp:TextBox ID="txtAge" runat="server" />
<asp:RangeValidator ID="rv" runat="server" ControlToValidate="txtAge"
MinimumValue="18" MaximumValue="60" Type="Integer"
ErrorMessage="Age must be 18-60" ForeColor="Red" Display="Dynamic" /><br />
Email: <asp:TextBox ID="txtEmail" runat="server" />
<asp:RegularExpressionValidator ID="rev" runat="server" ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ErrorMessage="Invalid email" ForeColor="Red" Display="Dynamic" /><br />
Password: <asp:TextBox ID="txtPass" runat="server" TextMode="Password" />
Confirm: <asp:TextBox ID="txtConfirm" runat="server" TextMode="Password" />
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txtConfirm"
ControlToCompare="txtPass" Operator="Equal"
ErrorMessage="Passwords do not match" ForeColor="Red" /><br />
<asp:ValidationSummary ID="vs" runat="server" HeaderText="Please correct:" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:Label ID="lblMsg" runat="server" />
</form>
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid) // server-side check
lblMsg.Text = "Form submitted successfully.";
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BCA 2021 Seventh Semester Advanced .NET Technology (TU board exam, 2021), TU BCA 2023 Seventh Semester Advanced .NET Technology (TU board exam, 2023), TU BCA 2025 Seventh Semester Advanced .NET Technology (TU board exam, 2025), TU BCA 2021 Seventh Semester Artificial Intelligence (TU board exam, 2021), TU BCA 2023 Seventh Semester Artificial Intelligence (TU board exam, 2023), TU BCA 2025 Seventh Semester Artificial Intelligence (TU board exam, 2025), TU BCA 2021 Seventh Semester Cloud Computing (TU board exam, 2021), TU BCA 2023 Seventh Semester Cloud Computing (TU board exam, 2023), TU BCA 2024 Seventh Semester Cloud Computing (TU board exam, 2024), TU BCA 2025 Seventh Semester Cloud Computing (TU board exam, 2025), TU BCA 2021 Seventh Semester Cyber Law and Professional Ethics (TU board exam, 2021), TU BCA 2023 Seventh Semester Cyber Law and Professional Ethics (TU board exam, 2023), TU BCA 2024 Seventh Semester Cyber Law and Professional Ethics (TU board exam, 2024), TU BCA 2025 Seventh Semester Cyber Law and Professional Ethics (TU board exam, 2025), TU BCA 2021 Seventh Semester Database Administration (TU board exam, 2021), TU BCA 2023 Seventh Semester Database Administration (TU board exam, 2023), TU BCA 2025 Seventh Semester Database Administration (TU board exam, 2025), TU BCA 2024 Seventh Semester E-Governance (TU board exam, 2024), TU BCA 2025 Seventh Semester E-Governance (TU board exam, 2025), TU BCA 2023 Seventh Semester Image Processing (TU board exam, 2023), TU BCA 2025 Seventh Semester Image Processing (TU board exam, 2025), TU BCA 2024 Seventh Semester Network Administration (TU board exam, 2024) and TU BCA 2025 Seventh Semester Network Administration (TU board exam, 2025). Answers are written for this site; check them against your class notes.