Preparations
Preparations
My current architecture is a simple client serrver 3 tier architecture with UI in ASP.NET, middle layer are
simple .NET classes and DAL is using enterprise application blocks. The UI(view) is responsible to take
user inputs , all my business validations are centrally located in middle layer and the data access layer is
responsible to execute stored procedure and SQL queries to SQL Server. Strongly typed business objects
are used to pass data from one layer to other layer. The database of the project is in a 3rd normal form."
Objects: Object is the basic unit of object-oriented programming.Objects are identified by its unique
name. An objectrepresents a particular instance of a class. There can be more than one instance of an
object. Each instance of an object can hold its own relevant data.
An Object is a collection of data members and associated member functions also known as methods.
Classes: Classes are data types based on which objects are created.Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represent a set of individual objects.
Characteristics of an object are represented in a class as Properties. The actions that can be performed by
objects becomes functions of the class and is referred to as Methods.
Example #1:
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents
individual Objects.In this context each Car Object will have its own, Model,Year of Manufacture, Colour,
Top Speed, Engine Power etc.,which form Properties of the Car class and the associated actions i.e.,
object functions like Start, Move, Stop form the Methods of Car Class.No memory is allocated when a
class is created. Memory is
allocated only when an object is created, i.e., when an instance of a class is created.
Abstraction: Abstraction means showing essential features and hiding non-essential features to the user.
When you provide the user name and password and click on submit button..It will show
Compose,Inbox,Outbox,Sentmails...so and so when you click on compose it will open...but user doesn't
know what are the actions performed internally....It just Opens....that is essential; User doesn't know
internal actions ...that is non-essential things...
Encapsulation: Encapsulation means which binds the data and code (or) writing operations and methods
in single unit (class).
For Example:
A car is having multiple parts..like steering,wheels,engine...etc..which binds together to form a single
object that is car. So, Here multiple parts of cars encapsulates itself together to form a single object that is
Car.
In real time we are using Encapsulation for security purpose...
For Eg.,
class Address
{
String name;
Srting H.no;
String Street name;
}
class LatestAddress extends Address
{
String City;
String State;
String Country;
}
public class Vishal
{
{
LatestAddress la = new LatestAddress();
//Assign variable accordingly...
}
}
In the above Example class LatestAddress getting all features from the Address class.
In the LatestAddress class we have total 6 properties..3 are inherited from Address class and 3 properties
are
incorporated. So In the class Vishal we are declaring the object of class LatestAddress and then assign
new variables using the properties of the previous base classes... So this is a nice example of inheritance..
Polymorphism :
Polymorphism means ability to take more than one form that an operation can exhibit different behavior
at different instance depend upon the data passed in the operation.
1>We behave differently in front of elders, and friends. A single person is behaving differently at
different time.
2> A software engineer can perform different task at different instance of time depending on the task
assigned to him .He can done coding , testing , analysis and designing depending on the task assign and
the requirement.
3> Consider the stadium of common wealth games. Single stadium but it perform multiple task like
swimming, lawn tennis etc.
4> If a girl is married and mother of 2 children doing teaching job then she is a women first ,, teacher in a
school when she is in school,,wife of someone at home,, mother of her children,, and obvious daughter of
someone & may be girl friend of someone (just kidding) means a woman plays diffent roles at different
times dats the polymorphism (many forms).
3. What is an interface?
An interface refers to a special type of class, which contains methods, but not their definition Only the
declaration of methods is allowed inside an interface. To use an interface, you cannot create objects.
Instead, you need to implement that interface and define the methods for their implementation.
1.
An abstract class doesn't provide full abstraction but an interface does provide full abstraction; i.e.
both a declaration and a definition is given in an abstract class but not so in an interface.
2. Using abstract we cannot achieve multiple inheritance but using an Interface we can achieve multiple
inheritance.
3. We can not declare a member field in an Interface.
4. We can not use any access modifier i.e. public, private, protected, internal etc. because within an
interface by default everything is public.
5. An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.
Abstract Class
We can not create an object of an abstract class and can call the method of abstract class with the help of
class name only.
Take a look at an Abstract class example,
The code window looks like this,
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace ConsoleApplication4
6. {
7. abstract class M1
8. {
9. public int add(int a, int b)
10. {
11. return (a + b);
12. }
13. }
14. class M2 :M1
15. {
16. public int mul(int a, int b)
17. {
18. return a * b;
19. }
20. }
21. class test
22. {
23. static void Main(string[] args)
24. {
25. M2 ob = new M2();
26. int result = ob.add(10, 20);
27. Console.WriteLine("the result is {0}", result);
28. Console.ReadLine();
29. }
30. }
31. }
An Interface
The syntax of an Interface looks like this,
interface
{
//Interface member
}
Note
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace ConsoleApplication3
6. {
7. interface MyInterface
8. {
9. void myMethod();
10. }
11. class MyClass : MyInterface
12. {
13. public static void Main()
14. {
15. MyClass cls = new MyClass();
16. cls.myMethod();
17. }
18. public void myMethod()
19. {
20. Console.WriteLine("welcome to MCN IT SOLUTION");
21. Console.ReadLine();
22. }
23. }
24. }
Abstract class
If a class is defined as abstract then we can't create an instance of that class. By the creation of the derived
class object where an abstract class is inherit from, we can call the method of the abstract class.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace ConsoleApplication13 {
6. abstract class mcn {
7. public int add(int a, int b) {
8. return (a + b);
9. }
10. }
11. class mcn1: mcn {
12. public int mul(int a, int b) {
13. return a * b;
14. }
15. }
16. class test {
17. static void Main(string[] args) {
18. mcn1 ob = new mcn1();
19. int result = ob.add(5, 10);
20. Console.WriteLine("the result is {0}", result);
21. }
22. }
23. }
In the above program we can call the method of the abstract class mcn with the help of an object of the mcn1
class which inherits from the class mcn. When we run the above program the output is the addition of 5 & 10
(i.e. 15) which is shown as,
Abstract method
An Abstract method is a method without a body. The implementation of an abstract method is done by a
derived class. When the derived class inherits the abstract method from the abstract class, it must override the
abstract method. This requirment is enforced at compile time and is also called dynamic polymorphism.
The abstract method is declared by adding the abstract modifier the method.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace ConsoleApplication14 {
6. abstract class test1 {
7. public int add(int i, int j) {
8. return i + j;
9. }
10. public abstract int mul(int i, int j);
11. }
12. class test2: test1 {
13. public override int mul(int i, int j) {
14. return i * j;
15. }
16. }
17. class test3: test1 {
18. public override int mul(int i, int j) {
19. return i - j;
20. }
21. }
22. class test4: test2 {
23. public override int mul(int i, int j) {
24. return i + j;
25. }
26. }
27. class myclass {
28. public static void main(string[] args) {
29. test2 ob = new test4();
30. int a = ob.mul(2, 4);
31. test1 ob1 = new test2();
32. int b = ob1.mul(4, 2);
33. test1 ob2 = new test3();
34. int c = ob2.mul(4, 2);
35. Console.Write("{0},{1},{2}", a, b, c);
36. Console.ReadLine();
37. }
38. }
39. }
In the above program, one method i.e. mul can perform various functions depending on the value passed as
parameters by creating an object of various classes which inherit other classes. Hence we can acheive
dynamic polymorphism with the help of an abstract method.
NOTE
When we use an override keyword the preference will be given to classes which has an instance created; in
case of inheritance, the preference will provide to the reference variable class.
Polymorphism means one name many forms. It is the main feature of OOPs. Polymorphism is an ability to
take more than one form but name will be the same. There are two types of polymorphism in NET.
When we create two or more method with the same name but different parameters or different sequence of
parameters and the time of calling compiler decide on the time of compilation which method should be called
on the basis of given arguments.
That is why it is called compile time polymorphism. We also call it static polymorphism.
It is implemented using overloaded methods and operators. Overloading process is called early binding. In
compile time polymorphism I have implemented overloading concepts with an example as given below:
Example 1
See the following example and in that example I have created two Add methods whose name are same but
parameters are different.
1. using System;
2.
3. namespace DemoTest
4. {
5. class AddClass
6. {
7. public void Add(int a, int b)
8. {
9. int r = a + b;
10. Console.WriteLine("Add two integer Number = " + r);
11. }
12. public void Add(string x, string y)
13. {
14. Console.WriteLine("Concatenation two string = " + x+y);
15. }
16. }
17.
18. class Program
19. {
20. static void Main(string[] args)
21. {
22. //add two integer values
23. AddClass addClassObj = new AddClass();
24. Console.WriteLine("Enter Two Integer values");
25. int m = int.Parse(Console.ReadLine());
26. int n = int.Parse(Console.ReadLine());
27. addClassObj.Add(m, n);
28.
29. //add two string values
30. Console.WriteLine("Enter Two String values");
31. string s1 = Console.ReadLine();
32. string s2 = Console.ReadLine();
33. addClassObj.Add(s1, s2);
34. Console.ReadLine();
35. }
36. }
37. }
When we create same name method in inherited class and what to override the functionality of base class,
then we use “Run Time Polymorphism”. It is called run time polymorphism because the compiler decides
which method should be called on the runtime. This is achieved through the use of virtual keyword with
method.
To override the base class method, we create base class method as virtual and derived class method as
override.
Example 2
See the following example where I have explained how can we override the base class method.
1. using System;
2.
3. namespace DemoTest
4. {
5. class ClassA
6. {
7. public virtual void Show()
8. {
9. Console.WriteLine("This is Show from ClassA");
10. }
11. }
12. class ClassB : ClassA
13. {
14. public override void Show()
15. {
16. Console.WriteLine("This is Show from ClassB");
17. }
18. }
19. class ClassC : ClassA
20. {
21. public override void Show()
22. {
23. Console.WriteLine("This is Show from ClassC");
24. }
25. }
26. class Program
27. {
28. static void Main(string[] args)
29. {
30. ClassA classAObj = new ClassA();
31. classAObj.Show(); // call classA "Show" method
32. classAObj = new ClassB();
33. classAObj.Show(); // call ClassB "Show" method
34. classAObj = new ClassC();
35. classAObj.Show(); // call ClassC "Show" method
36. Console.ReadLine();
37. }
38. }
39. }
So, finally you learned what polymorphism is and how many types of polymorphism. You also see the
two examples which are explaining the compile time polymorphism and run time polymorphism.
Method Overloading
Method Overloading is a type of polymorphism. It has several names like “Compile Time Polymorphism” or
“Static Polymorphism” and sometimes it is called “Early Binding”.
Method Overloading means creating multiple methods in a class with same names but different signatures
(Parameters). It permits a class, struct, or interface to declare multiple methods with the same name with
unique signatures.
Compiler automatically calls required method to check number of parameters and their type which are passed
into that method.
1. using System;
2. namespace DemoCsharp
3. {
4. class Program
5. {
6. public int Add(int num1, int num2)
7. {
8. return (num1 + num2);
9. }
10. public int Add(int num1, int num2, int num3)
11. {
12. return (num1 + num2 + num3);
13. }
14. public float Add(float num1, float num2)
15. {
16. return (num1 + num2);
17. }
18. public string Add(string value1, string value2)
19. {
20. return (value1 + " " + value2);
21. }
22. static void Main(string[] args)
23. {
24. Program objProgram = new Program();
25. Console.WriteLine("Add with two int parameter :" + objProgram.Add(3, 2));
26. Console.WriteLine("Add with three int parameter :" + objProgram.Add(3, 2, 8));
27. Console.WriteLine("Add with two float parameter :" + objProgram.Add(3 f, 22 f));
28. Console.WriteLine("Add with two string parameter :" + objProgram.Add("hello", "world"));
29. Console.ReadLine();
30. }
31. }
32. }
In the above example, you can see that there are four methods with same name but type of parameters or
number of parameters is different. When you call Add(4,5), complier automatically calls the method which
has two integer parameters and when you call Add(“hello”,”world”), complier calls the method which has
two string parameters. So basically in method overloading complier checks which method should be called at
the time of compilation.
Note: Changing the return type of method does not make the method overloaded. You cannot create method
overloaded vary only by return type.
Method Overriding
Method Overriding is a type of polymorphism. It has several names like “Run Time Polymorphism” or
“Dynamic Polymorphism” and sometime it is called “Late Binding”.
Method Overriding means having two methods with same name and same signatures [parameters], one
should be in the base class and other method should be in a derived class [child class]. You can override the
functionality of a base class method to create a same name method with same signature in a derived class.
You can achieve method overriding using inheritance. Virtual and Override keywords are used to achieve
method overriding.
1. using System;
2. namespace DemoCsharp
3. {
4. class BaseClass
5. {
6. public virtual int Add(int num1, int num2)
7. {
8. return (num1 + num2);
9. }
10. }
11. class ChildClass: BaseClass
12. {
13. public override int Add(int num1, int num2)
14. {
15. if (num1 <= 0 || num2 <= 0)
16. {
17. Console.WriteLine("Values could not be less than zero or equals to zero");
18. Console.WriteLine("Enter First value : ");
19. num1 = Convert.ToInt32(Console.ReadLine());
20. Console.WriteLine("Enter First value : ");
21. num2 = Convert.ToInt32(Console.ReadLine());
22. }
23. return (num1 + num2);
24. }
25. }
26. class Program
27. {
28. static void Main(string[] args)
29. {
30. BaseClass baseClassObj;
31. baseClassObj = new BaseClass();
32. Console.WriteLine("Base class method Add :" + baseClassObj.Add(-3, 8));
33. baseClassObj = new ChildClass();
34. Console.WriteLine("Child class method Add :" + baseClassObj.Add(-2, 2));
35. Console.ReadLine();
36. }
37. }
38. }
In the above example, I have created two same name methods in the BaseClass as well as in the ChildClass.
When you call the BaseClass Add method with less than zero value as parameters then it adds successfully.
But when you call the ChildClass Add method with less than zero value then it checks for negative value.
And the passing values are negative then it asks for new value.
So, here it is clear that we can modify the base class methods in derived classes.
Points to be remembered,
1. Inner Join
2. Outer Join
i. Left Outer Join
ii. Right Outer Join
iii. Full Outer Join
3. Cross Join
4. Self Join
tblDepartment
Now both tables are ready with their data. In tblEmployee, some DepartmentIds are not assigned to any
employee, hence their DepartmentId is showing as NULL.
So in total we've 25 Employees and 9 Departments. Now let's understand joins.
Inner Join
An Inner join requires matching records from both tables. You can use the "JOIN" or "INNER JOIN"
keyword to join you tables. The "INNER" keyword is optional.
1. SELECT <columns> from TABLE_A a
2. JOIN TABLE_B b
3. ON a.KEY = b.KEY;
1. SELECT e.FirstName+' '+ e.LastName as [Full Name], e.Salary, d.DeptName, d.Location FROM t
blEmployee e
2. INNER JOIN tblDepartment d
3. ON e.DepartmentId = d.DeptId;
Left Outer Join
You can use "LEFT OUTER JOIN" keywords to do Left Joining.
A left outer join returns a result containing both matching and non-matching rows from the left table. In other
words, it returns all rows from the left table. If the join condition matches 0 records in Table B then the join
will still return a row in the Result Set, but with NULL in each column from Table B.
1. SELECT <columns> from TABLE_A a
2. LEFT OUTER JOIN TABLE_B b
3. ON a.KEY = b.KEY;
1. SELECT e.FirstName+' '+ e.LastName as [Full Name], e.Salary, d.DeptName, d.Location FROM t
blEmployee e
2. LEFT OUTER JOIN tblDepartment d
3. ON e.DepartmentId = d.DeptId;
As you can see in the preceding output, non-matching rows are represented as NULL in both the columns.
But what if my manager says, instead if this NULL, some informative should be shown like, No Department
or NO Location or something, then what should we do?
So in such scenario, we'll make use of the "ISNULL" method, this method will allow us to show the data we
need to display instead of NULL.
1. SELECT e.FirstName+' '+ e.LastName as [Full Name], e.Salary, ISNULL(d.DeptName,'General') a
s Department, ISNULL(d.Location,'No Location') as Location FROM tblEmployee e
2. LEFT OUTER JOIN tblDepartment d
3. ON e.DepartmentId = d.DeptId
Now as you can see, this data is looking much better than the previous one. Instead of NULL, it says that
these many employees belong to "GENERAL Department" and their "Location is not yet specified".
Right Outer Join
"RIGHT OUTER JOIN" keywords are used to do Right Joining.
A right outer join is nearly the same as a left outer join. A right outer join retrieves matching data from both
of the tables + non-matching data from Table B.
1. SELECT <columns> from TABLE_A a
2. RIGHT OUTER JOIN TABLE_B b
3. ON a.KEY = b.KEY;
1. SELECT e.FirstName+' '+ e.LastName as [Full Name], e.Salary, d.DeptName, d.Location FROM t
blEmployee e
2. RIGHT OUTER JOIN tblDepartment d
3. ON e.DepartmentId = d.DeptId;
NULL will appear in columns from Table A for those records that have no match in Table B. You can
replace the NULL value with whatever value you want using the ISNULL() method as shown for Left Outer
Join.
Full Outer Join
To do a Full outer join you can use the "FULL OUTER JOIN" keywords.
In a full outer join, the result set will display all the data from Table A and Table B. For every non-matching
row in a full outer join the unmatched data has NULL.
1. SELECT <columns> from TABLE_A a
2. FULL OUTER JOIN TABLE_B b
3. ON a.KEY = b.KEY;
1. SELECT e.FirstName+' '+ e.LastName as [Full Name], e.Salary, d.DeptName, d.Location FROM t
blEmployee e
2. FULL OUTER JOIN tblDepartment d
3. ON e.DepartmentId = d.DeptId;
Cross Join
Use "CROSS JOIN" keywords to do cross joining.
A cross join returns the Cartesian product of rows from both tables in the join. In other words, it'll produce
rows that combines rows from Table A with each row from Table B.
1. SELECT <columns> from TABLE_A a
2. CROSS JOIN TABLE_B b
1. SELECT e.FirstName+' '+ e.LastName as [Full Name], e.Salary, d.DeptName, d.Location FROM t
blEmployee e
2. CROSS JOIN tblDepartment d
When you run the cross join command, you'll see output of "225" rows.
25 Rows from tblEmployee
09 Rows from tblDepartment
Cross Join => [25 X 09] = 225 Rows.
Self Join
A self-join is the joining of the table to itself.
1. select e1.EmpId,e1.FirstName, e1.LastName, e1.Salary, e2.EmpId, e2.FirstName, e2.LastName,e2.S
alary from tblEmployee e1
2. JOIN tblEmployee e2
3. on e1.FirstName = e2.FirstName
4. ORDER by e1.FirstName;
If you see the output, tblEmployee table is joined with itself by FirstName.
Some of the names like Jyoti, Rahul and so on are repeated 4 times, because there're 2 people with the same
FirstName and if we self-join the FirstName of one table with the same FirstName of another table then it'll
produce 4 output as represented below.
First "Jyoti Kakawat" will make a pair with herself (1 row), then she'll make a pair with "Jyoti Mishra" (2
rows). Then, "Jyoti Mishra" will make a pair with herself (3 rows) and then she'll also make another pair with
"Jyoti Kakawat" (4 rows).
It returns the combined tuple between It returns the combined tuple from a specified
1. two or more tables. table even join condition will fail.
If tuples are more. Then INNER JOIN Generally, The OUTER JOIN is slower than
4. works faster than OUTER JOIN. INNER JOIN. But except for some special cases.
JOIN and INNER JOIN both clauses FULL OUTER JOIN and FULL JOIN both
6. work the same. clauses work the same.
SQL Syntax:
SQL Syntax: select *
select * from table1 LEFT OUTER JOIN / RIGHT
from table1 INNER JOIN / JOIN table2 OUTER JOIN /
ON table1.column_name = FULL OUTER JOIN / FULL JOIN table2 ON
7. table2.column_name; table1.column_name = table2.column_name;
Class Structure
Allocation of large reference type is cheaper than Allocation and de-allocation is cheaper in value type
allocation of large value type. as compare to reference type.
Class is generally used in large programs. Struct are used in small programs.
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where
the value is being stored. In other words, a reference type contains a pointer to another memory location
that holds the data.
The following image shows how the system allocates the memory for the above string variable.
Memory Allocation of
Reference Type Variable
As you can see in the above image, the system selects a random location in memory (0x803200) for the
variable s. The value of a variable s is 0x600000, which is the memory address of the actual data value.
Thus, reference type stores the address of the location where the actual value is stored instead of the value
itself.
String
Arrays (even if their elements are value types)
Class
Delegate
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides
a given software application into three interconnected parts, so as to separate internal representation of
information from the way that information is presented to or accepted from the user.
MVC is a framework for building web applications using an MVC (Model View Controller) design:
The Model represents the application core (for instance a list of database records).
The View displays the data (the database records).
The Controller handles the input (to the database records).
The MVC model also provides full control over HTML, CSS, and JavaScript.
MVC architecture represents the domain-specific data and business logic. It maintains the data of the
application, model data hold the data in public property.
Namespace mvc.Models
In Model, we can apply validation to the property using Data Annotation instead of applying on the client
side. For adding data Annotation we need to add the reference
“System.ComponentModel.DataAnnotations assembly”
Like we apply on StudentId
Eg.
[Display(Name=”StudentId ”)]
[Required(ErrorMessage=”StudentId is Required”)]
View : View is the User Interface where The user can display its own data and can modify its data, In this,
the data is passed from the model to the view. The view has a different folder with the same name as of
controller and has different views in it of different actions.
User View : To create this view use page template. The inherited class name will be available in <
%@ page directive with inherits attributes.
Master Page View : To create a master page view we use a template known as “MVC2 view master
page.it have a default extension of.master.
Partial View : Partial View is the same as UserController in asp.net it is inherited from the
System.Web.Mvc
Controller: It is the most essential part of the MVC in asp.net since it is the first recipient which interacts
with HTTP and finds the model and actions. So it is the controller which decides which model should be
selected and how to carry the data from the respective view, a controller is inherited from the
System.Mvc.Controller. The routing map of the controller is decided in RouteConfig.cs which is under App
Start Folder.
Eg, http://localhost:61465/Employee/Mark
In MVC, routing is a process of mapping the browser request to the controller action and return response
back. Each MVC application has default routing for the default HomeController. We can set custom
routing for newly created controller.
Controller act as a mediator between view and model. it is responsible to control the data
transmission between the model and the view. It maps the user action into model updates.The
controller layer is helpful to select the most appropriate view and delivers it to the user.
16. How does public, private, internal (friend), protected, etc affect the class?
public: The type or member can be accessed by any other code in the same assembly or another
assembly that references it.
private: The type or member can be accessed only by code in the same class or struct.
protected: The type or member can be accessed only by code in the same class, or in a class that is
derived from that class.
internal: The type or member can be accessed by any code in the same assembly, but not from
another assembly.
protected internal: The type or member can be accessed by any code in the assembly in which it's
declared, or from within a derived class in another assembly.
private protected: The type or member can be accessed only within its declaring assembly, by code in
the same class or in a type that is derived from that class.
Collections standardize the way of which the objects are handled by your program. In other words, it
contains a set of classes to contain elements in a generalized manner. With the help of collections, the user
can perform several operations on objects like the store, update, delete, retrieve, search, sort etc.
C# divide collection in several classes, some of the common classes are shown below:
ADO.NET consists of managed classes that allows .NET applications to connect to data sources
such as Microsoft SQL Server
connection string is a string that specifies information about a data source and the means of connecting to
it.
20. What does a WHERE clause do?
WHERE clause in SQL is used to filter records that are necessary, based on specific conditions
23. call by value and call by reference and where we should use?
24. virtual function
47. HTTPGET,HTTPPOST
ASP.NET MVC model binder allows you to map Http Request data with the model.
Http Request data means when a user makes a request with form data from the browser
to a Controller, at that time, Model binder works as a middleman to map the incoming
HTTP request with Controller action method
The Web is stateless: That means every time a page gets loaded a new instance is used
to create it. There are many scenarios in which we need to save some values for
further usage. Let'ss say I have counter variable and need to restore its value on each
page load, so thar I can store it in sessions in order to use it again. Another example is
username to show on page, etc.
1. InProc
2. StateServer
3. SQLServer
Session in MVC
In MVC the controller decides how to render view, meaning which values are accepted
from View and which needs to be sent back in response. ASP.NET MVC Session state
enables you to store and retrieve values for a user when the user navigatesto other
view in an ASP.NET MVC application.
Let us take each task one by one, first we will take ViewBag:
ViewBag is a property of controllerBase. It’s nature is dynamic, that means we are able
to add dynamic properties without compiling time errors. It allows us to share the
value from controller to view.
Let’s work on the assignment by adding current date and time from controller to view
using ViewBags .
1. @{
2. Layout = null;
3. }
4.
5. <!DOCTYPEhtml>
6. <html>
7. <head>
8. <metaname="viewport"content="width=device-width"/>
9. <title>Index</title>
10. </head>
11. <body>
12. <div>
13. @ViewBag.Greeting is the current time....
14. </div>
15. </body>
16. </html>
1. public ActionResult Index()
2. {
3. ViewBag.Greeting = "Current Time is " + DateTime.Now;
4. return View();
5.
6. }
Step 6: Run your application and you will find the following response.