SRIJAN_BASNET_ DOTNET_LAB
SRIJAN_BASNET_ DOTNET_LAB
LANGUAGE PRELIMINARIES
OBJECTIVE:
TO LEARN ABOUT THE VARIOUS PRELIMINARIES FOR THE C#
PROGRAMMING LANGUAGE
C# SYNTAX:
THEORY:
C# is a high level, general-purpose, object-oriented programming language
developed by Microsoft. A C# Program may consists of the following parts:
• Namespace Declaration
• Class
• Class Methods
• Class Attributes
• Main Method
• Statements and Expressions
• Comments
SOURCE PROGRAM:
using System;
namespace SyntaxLearning
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we were able to demonstrate a basic C# console application
that utilizes essential programming elements for basic C# Syntax.
BASIC LANGUAGE CONSTRUCTS (VARIABLES AND DATA TYPES):
THEORY:
Variables are special containers that hold the data at specific memory locations. Variables can
Either Be Numeric, String, Characters , Booleans , Decimal , Date and so on. The syntax for the
declaration of variables in C# is given as:
data_type variable_name;
e.g.
int age;
Different Data Types in a C# program are:
Data Types Keywords
Integer int
Floating float
Character char
Boolean bool
Decimal decimal
C# also has the Reference data type which stores reference to the value in the managed heap.
Some of The Reference Data Types are:
• Class Type
• String Type
• Delegate Type
• Interface Type
• Array Type
SOURCE PROGRAM:
using System;
namespace DataTypeShowcase
{
class Program
{
static void Main(string[] args)
{
int yearsOfExperience = 5;
float averageScore = 85.6f;
string firstName = "Alice";
bool hasDrivingLicense = false;
decimal accountBalance = 2500.75m;
char grade = 'A';
int[] attendanceDays = { 1, 3, 5, 7, 9, 11, 13, 15 };
if (hasDrivingLicense)
{
Console.WriteLine("You have a driving license.");
}
else
{
Console.WriteLine("You do not have a driving license.");
}
Console.WriteLine($"Name: {firstName}, Experience: {yearsOfExperience} years, Average
Score: {averageScore}, Grade: {grade}, Account Balance: {accountBalance}");
Console.WriteLine("Attendance Days:");
foreach (int day in attendanceDays)
{
Console.Write(day + " ");
}
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we were able to showcase the various data types in the C#
programming language.
FLOW CONTROL STATEMENTS:
THEORY:
Flow Control Statement is the programming construct that determines which part of the code is
to be executed next using conditions and loops. The two Types of flow control statements are
Conditional Statements and Loop Statements.
if/else statements: In C#, if-else statements are control structures that enable the program to
execute specific blocks of code based on evaluated boolean conditions.
Syntax:
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
switch case statements: C# also provides switch statements for multi-case comparisons, which
can be seen as a form of nested if-else constructs optimized for value-based comparisons.
Syntax:
switch (expression)
{
case value1:
// Code block 1
break;
case value2:
// Code block 2
break;
...
default:
// Default code block
}
looping statements: Loops in C# allows you to execute the statements or group of statements
repeatedly until a certain condition is met. C# has the following types of looping statements. -
for loop
- while loop
- do/while loop
- foreach loop
SOURCE PROGRAM:
using System;
namespace ConditionalShowcase
{
class Program
{
static void Main(string[] args)
{
int age = 20;
if (age >= 18)
{
Console.WriteLine("You can vote.");
}
else
{
Console.WriteLine("You cannot vote.");
}
}
}
}
OUTPUT:
SOURCE PROGRAM:
using System;
namespace ConditionalShowcase
{
class Program
{
static void Main(string[] args)
{
int dayOfWeek = 1;
switch (dayOfWeek)
{
case 1:
Console.WriteLine("Sunday");
break;
case 2:
Console.WriteLine("Monday");
break;
case 3:
Console.WriteLine("Tuesday");
break;
case 4:
Console.WriteLine("Wednesday");
break;
case 5:
Console.WriteLine("Thursday");
break;
case 6:
Console.WriteLine("Friday");
break;
case 7:
Console.WriteLine("Saturday");
break;
default:
Console.WriteLine("Invalid day of the week");
break;
}
}
}
}
OUTPUT:
SOURCE PROGRAM:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("For Loop Example");
for (int i = 0; i < 5; i++)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
Console.WriteLine("While Loop Example");
string sentence = "The fox Jumps over the world";
int j = 0;
int countWords = 0;
while (j < sentence.Length)
{
if (sentence[j] == ' ')
{
countWords++;
}
j++;
}
Console.WriteLine("Number of words in the sentence: " + (countWords +
1)); Console.WriteLine("\n");
Console.WriteLine("Do While Loop Example");
int age;
do
{
Console.Write("Enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
Console.WriteLine("Not Allowed to vote");
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate various flow control
statements in C# programming language.
ARRAYS:
THEORY:
An Array is the collection of the same type of variable.
Syntax for array Declaration is given as:
data_type[] arr_name;
e.g.
string[] strarr=new string[5] //this is how we allocate along with size
Jagged Arrays:
In C#, a jagged array is an array of arrays, where each element of the main array is itself an array.
Unlike a multidimensional array, the sub-arrays in a jagged array can be of different lengths,
hence the term "jagged."
SOURCE PROGRAM:
using System;
namespace ArrayShowcase
{
class Program
{
static void Main(string[] args)
{
int[] regularArray = { 1, 2, 3, 4, 5 };
Console.WriteLine("Regular array:");
for (int i = 0; i < regularArray.Length; i++)
{
Console.Write(regularArray[i] + " ");
}
Console.WriteLine();
Console.WriteLine("Jagged array:");
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write($"Row {i + 1}: ");
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the use of both a simple string
array and a jagged array in C# programming language.
CLASS, METHODS:
THEORY:
In C# a class is a blueprint or template for creating objects (instances) that encapsulate data
(fields or properties) and behavior (methods or functions). It is a fundamental concept in object
oriented programming (OOP) and serves as the foundation for defining custom data types. Key
Features of a Class Are:
1. Fields: Variables That Hold the Data
2. Properties: Special methods that provide controlled access to Fields
4. Methods: Functions that define the behavior of the class.
5. Constructors: Special Methods that Helps to initialize the Object
6. Access Modifiers: Keywords like public private protected that control the visibility of the class
members.
7. Inheritance: A Class can inherit fields and methods from another class (base class) to promote
code reuse.
In C#, a method is a block of code that performs a specific task or operation. It is a fundamental
building block of a program and is used to encapsulate reusable logic. Methods are defined
within a class or struct and can be called (invoked) to execute their code.
SOURCE PROGRAM:
using System;
namespace ClassShowcase
{
class Program
{
static void Main(string[] args)
{
Person person = new Person("Ana", 25);
person.DisplayInfo();
person.Greet();
}
}
class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {name}, Age: {age}");
}
public void Greet()
{
Console.WriteLine($"Hello, {name}.");
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the use of a class and methods
in C# programming language with fields, properties, a constructor, .
EXCEPTION HANDLING:
THEORY:
The Exceptional Handling in C# is done using try, catch and finally blocks. This is the
Mechanism to detect and handle the runtime errors in code. The .NET framework provides the
built-in classes for common exceptions. The exceptions can be because of user, logic or system
errors.
Syntax for Exception Handling is given as:
try{
// Statement which can cause an exception
}
catch(Type x){
//Statement for handling the exception
}
finally{
// Final Code After The Exception Handling i.e. cleanup code
}
- The try block contains the code that might throw an exception.
- The catch block handles the exception if it occurs.
- The finally block contains code that will always execute, whether an exception occurs or
not. It is typically used for cleanup tasks (e.g., closing files or releasing resources). - The
throw statement is used to explicitly throw an exception.
SOURCE PROGRAM :
using System;
namespace ExceptionHandlingShowcase
{
class Program
{
static void Main(string[] args)
{
try
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter another number: ");
int divisor = int.Parse(Console.ReadLine());
int result = number / divisor;
Console.WriteLine($"Result: {result}");
}
catch (FormatException ex)
{
Console.WriteLine($"Error: Invalid input. {ex.Message}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: Cannot divide by zero. {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed.");
}
}
}
}
OUTPUT :
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate exception handling in C# by
attempting to divide two user-input numbers, catching specific exceptions like
DivideByZeroException and ensuring the finally block executes to indicate completion.
LAB - 2:
OOP CONCEPTS
INHERITANCE:
THEORY:
Inheritance is a key feature of Object-Oriented Programming (OOP) that allows a class
(child/derived) to inherit members (fields, methods, properties) from another class (parent/base).
i. Single Level Inheritance: In single-level inheritance, a child class inherits from a single parent
class.
Syntax:
class Parent{
//methods and properties
}
class Children:Parent{
//Children methods and properties
}
ii. Multi-Level Inheritance: In multi-level inheritance, a class is derived from another derived
class, forming a chain of inheritance.
Syntax:
class GranParent{
//methods and properties
}
SOURCE PROGRAM:
using System;
namespace InheritanceShowcase
{
interface IGreet
{
void Greet();
}
class Person : IGreet
{ protected string name;
public Person(string name)
{
this.name = name;
}
public virtual void DisplayInfo()
{Console.WriteLine($"Name: {name}");
}
public void Greet()
{ Console.WriteLine($"Hello, my name is {name}.");
}
}
class Employee : Person
{
protected int employeeId;
public Employee(string name, int employeeId) : base(name)
{
this.employeeId = employeeId;
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Employee ID: {employeeId}");
}
}
class Manager : Employee
{
private string department;
public Manager(string name, int employeeId, string department) : base(name, employeeId)
{
this.department = department;
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Department: {department}");
}
}
class Program
{
static void Main(string[] args)
{
Manager manager = new Manager("Srijan", 777, "Automations");
manager.DisplayInfo();
manager.Greet();
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate multilevel inheritance and
interface in the C# programming language.
CONSTRUCTOR, PROPERTIES AND METHODS:
THEORY:
i. Default Constructor
A constructor without parameters.
Syntax:
class ClassName
{
public ClassName()
{
// Constructor logic
}
}
SOURCE PROGRAM:
using System;
namespace PropertyAndConstructorShowcase
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person()
{
Name = "Unknown";
Age = 0;
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.DisplayInfo();
Person person2 = new Person("Zephyr", 25);
person2.DisplayInfo();
Person person3 = new Person(person2);
person3.DisplayInfo();
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrates the use of constructors,
methods, and properties in C# programming language.
METHOD OVERLOADING AND OVERRIDING:
THEORY:
Method Overloading allows multiple methods in the same class to have the same name but
different parameters. The method signature must differ in:
1. Number of parameters
2. Type of parameters
3. Order of parameters
SOURCE PROGRAM:
using System;
namespace MethodOverloadingShowcase
{
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
public double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Console.WriteLine("Add two integers: " + calculator.Add(1, 2));
Console.WriteLine("Add three integers: " + calculator.Add(1, 2, 3));
Console.WriteLine("Add two doubles: " + calculator.Add(1.1, 2.2));
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment,This program demonstrates Method Overloading by
defining multiple Add methods with different parameters and Method Overriding by
allowing the Dog class to override the Eat method of the Animal class, showcasing both
compile-time and runtime polymorphism in C#.
LAMBDA EXPRESSIONS:
THEORY:
Lambda expressions are a concise way to represent anonymous functions in C#. They are
primarily used in LINQ queries and delegate-based programming. The term "lambda" comes
from lambda calculus, a formal system for defining functions.
Syntax:
(parameters) => expression
OR
(parameters) => { statement(s) }
e.g.
y => y * y
This expression takes a parameter y and returns its square (y * y).
• Expression Lambdas:
Lambda expressions that contain only a single expression on the right-hand side are
known as expression lambdas.
• Async Lambdas:
Lambda expressions can also be used with asynchronous programming by incorporating
the async keyword:
SOURCE PROGRAM:
using System;
using System.Collections.Generic;
using System.Linq;
namespace LambdaExpressionShowcase
{
class Program
{
static void Main(string[] args)
{
Func<int, int> triple = (a) => a * 3;
Console.WriteLine("Tripling a number using lambda: " + triple(7));
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate various lambda
expressions in C# programming language.
LAB - 3:
ASP .NET MVC
2. View: View in MVC represents the interface of the program . View display model data to
the user and enables them to modify them. View in ASP.NET is HTML,CSS and some
specific syntax (Razor) that makes it easy to communicate with the model and controller.
View is the user Interface.
3. Controller: Controller Handles The User Request . Typically, the user uses the view and
raises the HTTP Request, which will be handled by the controller. The controller process
the request and returns the appropriate view as a response. Controller is the request
handler.
SOURCE PROGRAM:
//Models/Person.cs
namespace SimpleMvcApp.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
//Controllers/PersonController.cs
using Microsoft.AspNetCore.Mvc;
using SimpleMvcApp.Models;
using System.Collections.Generic;
namespace SimpleMvcApp.Controllers
{
public class PersonController : Controller
{
public IActionResult Index()
{
var people = new List<Person>
{
new Person { Id = 1, Name = "Alice", Age = 30 },
new Person { Id = 2, Name = "Bob", Age = 25 },
new Person { Id = 3, Name = "Charlie", Age = 35 }
};
return View(people);
}
}
}
Views/Person/Index.cshtml
@model IEnumerable<SimpleMvcApp.Models.Person>
<h1>People</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
@foreach (var person in Model)
{
<tr>
<td>@person.Id</td>
<td>@person.Name</td>
<td>@person.Age</td>
</tr>
}
</tbody>
</table>
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the Model View Controller
concept in an ASP.NET Core web app .
RAZOR SYNTAX AND HTML TAG HELPER:
THEORY:
Razor is a lightweight and powerful syntax used for embedding server-side code into HTML in
ASP.NET Core MVC and Razor Pages. It allows developers to mix C# code with HTML in a
clean and readable way.
Inline Expressions:(@expressions)
<p>Current Year: @DateTime.Now.Year</p>
Conditional Statements:
@{
int age = 20;
}
@if (age >= 18)
{
<p>You are an adult.</p>
}
else
{
<p>You are a minor.</p>
}
Loop:
@{
var fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
<ul>
@foreach (var fruit in fruits)
{
<li>@fruit</li>
}
</ul>
<p>Name: @Model.Name</p>
<p>Age: @Model.Age</p>
Razor Comments:
@*
This is a Comment for The Razor cshtml
*@
Tag Helpers enable the server-side code to participate in creating and rendering HTML Elements
in Razor files. There are many built-in tag helpers for some common tasks, such as creating
forms, links, loading assets, etc. Tag Helpers are authorized in C# and they Target HTML
elements based on the element name, the attribute name, or the parent tag.
Tag Helpers must be enabled in Razor Views. By default, they are available in ASP.NET
Core MVC.
If not already enabled, add this line at the top of _ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
SOURCE PROGRAM:
// Controllers/PersonController.cs
using Microsoft.AspNetCore.Mvc;
using SimpleMvcApp.Models;
using System.Collections.Generic;
namespace SimpleMvcApp.Controllers
{
public class PersonController : Controller
{
private static List<Person> people = new List<Person>
{
new Person { Id = 1, Name = "Alice", Age = 23 },
new Person { Id = 2, Name = "Bob", Age = 24 },
new Person { Id = 3, Name = "Charlie", Age = 25 }
};
[HttpPost]
public IActionResult Create(Person person)
{
person.Id = people.Count + 1;
people.Add(person);
return RedirectToAction("Index");
}
}
}
//Person/Index.cshtml
@model IEnumerable<SimpleMvcApp.Models.Person>
@{
<h1>@ViewData["Title"]</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>@person.Id</td>
<td>@person.Name</td>
<td>@person.Age</td>
</tr>
</tbody>
</table>
<p>
</p>
//Person/Create.cshtml
@model SimpleMvcApp.Models.Person
@{
<h1>@ViewData["Title"]</h1>
<div class="form-group">
<div class="form-group">
</div>
<div class="form-group">
</div>
</form>
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the Razor Syntax and HTML
Tag Helpers used in ASP.NET Core MVC Web App.
LAB - 4:
ADO.NET
THEORY:
ADO.NET (ActiveX Data Objects for .NET) is a core component of the .NET Framework,
introduced in the early 2000s, designed for efficient data access and manipulation. It enables
applications to interact with databases, XML, and other data sources, offering both connected
and disconnected architectures.
Different Classes in The ADO NET are:
Connection Classes
• Purpose: Establish and manage a connection to a data source.
• Common Implementations:
o SqlConnection (for SQL Server)
o OleDbConnection (for OLE DB providers, e.g., Excel, Access)
o OdbcConnection (for ODBC drivers)
o OracleConnection (for Oracle databases)
• Key Methods:
o Open(): Opens the connection.
o Close(): Closes the connection.
o BeginTransaction(): Starts a database transaction.
Command Classes
• Purpose: Execute SQL queries, stored procedures, or commands against a data source. •
Common Implementations:
o SqlCommand, OleDbCommand, OdbcCommand, etc.
• Key Methods:
o ExecuteNonQuery(): Executes non-query commands (e.g., INSERT, UPDATE,
DELETE).
o ExecuteScalar(): Returns a single value (e.g., result of COUNT(*)).
o ExecuteReader(): Returns a DataReader for read-only, forward-only data access.
• Properties:
o CommandText: The SQL query or stored procedure name.
o CommandType: Text (default), StoredProcedure, or TableDirect.
DataReader Classes
• Purpose: Read data in a fast, forward-only, read-only stream. Ideal for large datasets. •
Common Implementations:
o SqlDataReader, OleDbDataReader, etc.
• Key Methods:
o Read(): Advances to the next record.
o GetValue(), GetString(), etc.: Retrieve column values.
Transaction Classes
• Purpose: Ensure atomicity and consistency in database operations. •
Common Implementations:
o SqlTransaction, OleDbTransaction, etc.
• Key Methods:
o Commit(): Saves changes to the database.
o Rollback(): Reverts changes.
SOURCE PROGRAM:
using System;
using System.Data.SqlClient;
namespace StudentAdmissionApp
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=localhost;Database=master;Trusted_Connection=True;";
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate database integration in a .NET
application using ADO.NET by performing basic insert, delete and read operations.
LAB - 5:
ENTITY FRAMEWORK
THEORY:
Entity Framework Core (EF Core) is a lightweight, extensible, and cross-platform version
of the popular Entity Framework data access technology. It is an Object-Relational Mapper
(ORM) that enables .NET developers to work with a database using .NET objects,
eliminating the need for most of the data-access code that developers usually need to write.
EF Core supports a variety of database engines, making it a versatile tool for .NET
applications.
Create a DbContext: The DbContext is the bridge between your entity classes and the
database. It manages the entities, tracks changes, and performs database operations. You define
a DbContext class that includes DbSet<TEntity> properties for each entity.
Configure the Database Connection: In your application’s configuration, you specify the
database provider (e.g., SQL Server, SQLite, PostgreSQL) and the connection string.
Apply Migrations: If you’re using the Code-First approach, you can create and apply
migrations to create or update the database schema based on your entity classes.
Query and Save Data: Use LINQ or raw SQL to query the database and retrieve data. Modify
the entities as needed and save changes back to the database using the SaveChanges or
SaveChangesAsync method.
SOURCE PROGRAM:
//Student.cs
namespace StudentAdmissionAppEF
{
public class Student
{
public int Id { get; set; }
public string? StudentName { get; set; }
public string? Elective { get; set; }
}
}
//StudentContext.cs
using Microsoft.EntityFrameworkCore;
namespace StudentAdmissionAppEF
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
optionsBuilder.UseSqlServer("Server=localhost;Database=StudentDB;Trusted_Connection=True;Tr
ustServerCertificate=True;");
}
}
}
//Program.cs
using System;
using System.Linq;
namespace StudentAdmissionAppEF
{
class Program
{
static void Main(string[] args)
{
using (var context = new StudentContext())
{
// Ensure database is created
context.Database.EnsureCreated();
// Insert data
var student = new Student { StudentName = "John Doe", Elective = "Mathematics" };
context.Students.Add(student);
context.SaveChanges();
Console.WriteLine("Data inserted successfully.");
// Read data
var students = context.Students.ToList();
Console.WriteLine("Students:");
foreach (var s in students)
{
Console.WriteLine($"Id: {s.Id}, StudentName: {s.StudentName}, Elective: {s.Elective}");
}
// Delete data
var studentToDelete = context.Students.FirstOrDefault(s => s.StudentName == "John
Doe");
if (studentToDelete != null)
{
context.Students.Remove(studentToDelete);
context.SaveChanges();
Console.WriteLine("Data deleted successfully.");
}
}
}
}
}
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate database integration in a .NET
application using entity framework by performing basic insert, delete and read operations.
LAB - 6:
STATE MANAGEMENT
THEORY:
HTTP is a stateless protocol. HTTP requests are independent messages that
don’t retain user values or app states. We need to take additional steps to manage states
between the requests.
Some of The Approach for State Management in ASP .NET Core App
Session State:
Session state is an ASP.NET Core mechanism to store user data while the user browses
the application. We should store the critical application data in a database and we should cache it
in the session only as a performance optimization if required.
ASP .NET Core maintains the session state by providing a cookie to the client that
contains a sessionID. The browser sends this cookie to the application with each request. The
application uses the sessionID to fetch the session data.
While working with Session State, we should keep the following things in mind:
TempData:
TempData persists data between requests, but only until it is read. Once accessed, the data is
removed automatically unless it is explicitly kept using:
SOURCE PROGRAM:
// Controllers/StateController.cs
namespace StateManagementApp.Controllers
return View();
ViewBag.SessionData = sessionData;
ViewBag.SessionValue1 = HttpContext.Session.GetString("SessionValue1");
ViewBag.SessionValue2 = HttpContext.Session.GetString("SessionValue2");
return View();
// Get temp data using Peek (does not mark for deletion)
ViewBag.TempData = tempData;
TempData.Keep("TempData");
return View();
HttpContext.Session.SetString("SessionValue1", "Value1");
HttpContext.Session.SetString("SessionValue2", "Value2");
return RedirectToAction("Index");
// Clear session
HttpContext.Session.Clear();
return RedirectToAction("Index");
//State/Index.cshtml
@{
ViewData["Title"] = "Index";
<h1>Index</h1>
<p>
</p>
<p>
</p>
<p>
</p>
<p>
</p>
//ShowTempData.cshtml
@{
@{
OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate various state management
techniques in ASP.NET Core.