MVC Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 101

MVC NOTES

Syllabus of MVC

UNIT-I
Introduction to AJAX and JQuery, Simple Program of JQuery, Description and
Implementation of Following using Jquery- Accordion, AutoComplete, Calendar
Extender, Animation, Resizable Controls, RoBot – CAPTCHA

UNIT-II
A Brief History of Web Development , Difference between Asp.net and MVC,
Introduction of ASP. NET MVC, Merit and Demerits of ASP.NET MVC, MVC
Architecture (Model, View and Controler), MVC scaffolding

UNIT-III
Razor Engine & ASPX Engine, Use of Razor Engine in View , Transfer Data From
View to Controller, Variable Declare in Razor , Comments in Razor View, if else and
Looping and For Each in Razor, Description and Use of Session in MVC(View Bag,
Temp Data, ViewData), MVC Routing Engine Overview, Understand the default
Route, Routing with Example

UNIT-IV
JSON (Java Script Object Notation), Authentication and Authorization in MVC,
Performance Improvement Techniques- Bundling and Minification, Exception
Handling, MVC Filter(Action Filter, Authorization Filter) Entity Frame Work
Including lamda expression and linq, Basic Html helper classes, Bootstrap

Unit – 1
1. Introduction to AJAX
Stands for Asynchronous JavaScript And XML

 AJAX is used as an extension for ASP.NET to develop and implements the


AJAX functionality. ASP.NET AJAX has both client side and server side
component to develop the web application that can update the information
on a web application without reloading the page completely. This means
that it is possible to update parts of a web page, without reloading the
whole page.The following are the advantages of using AJAX:

 AsynchronousEnable Asynchronous call to a web server without making the


user wait for the data.
 Minimal transfer of data Helps in sending only a part of the modified data to
a web server to minimize the network traffic and perform the operation
quicker.
 Minimal Processing on a web server Help in minimizing the processing on a
web server as only the necessary data is sent to it. Moreover the web server
is not required to send a full page back to the user.

 Context Help in reducing the burden on a web server by sending a request


back to the server through the client side script. AJAX- Based application
implement partial-page post back instead of full-page post backs, it reduce
the data traffic between client and server

AJAX IN WEB DEVELOPMENT


The use of the AJAX in the web development is to enhance the performance of the
website,it is used for partial rendering means without uploading the entire page
we can only upload the specific portion of the website,so the entire load of the
website will not go to server.

 The method of exchanging data with a server, and updating parts of a web
page – without reloading the entire page.
 Ajax is a client-side script that communicates to and from a server/database

without the need for a postback or a complete page refresh.


 “Asynchronous” means that multiple events are happening independently of
one another. 

 Benefits of Ajax

1. Callbacks:Ajax is used to perform a callback, making a quick round trip


to and from the server to retrieve and/or save data without posting the
entire page back to the server.

By not performing a full postback and sending all form data to the
server, network utilization is minimized and quicker operations occur.

There is no need to process all form elements, process the ViewState,


send images back to the client, or send a full page back to the client.

2. Making Asynchronous Calls: Ajax allows you to make asynchronous


calls to a web server. This allows the client browser to avoid waiting for
all data to arrive before allowing the user to act once more.
3. User-Friendly: Because a page postback is being eliminated, Ajax
enabled applications will always be more responsive, faster and more
user-friendly.
4. Increased Speed: 
5. Easier navigation
6. Better interactivity
7. Backed by reputed brands
8. Platform independent

Ajax callbacks can be done by instantiating an XMLHttpRequest object in


the client-side JavaScript. The XMLHttpRequest object can be used to
directly call server-side objects like pages and web services. These pages
and web services will either save and/or return data.

Disadvantages:-

1. It is built on javascript while javasript is secure and has been heavily


used by websites for a long period of time. A percentage of website
surfers to turn javascript functionality off on their browser rendering
the Ajax application useless.
2. The back and refresh button are rendered useless means clicking the
back or refresh button would take you to an entirely different web
page or to the beginning of your dynamic web page was processing.
This is the main drawback behind ajax.

Important points of ajax

3. This is a cross platform technology which speeds up response time.


4. Ajax is not a programming language or a tool, but a concept.
5. Ajax is invented in the year 2005. It was invented my google and
Microsoft.
6. Example of application using AJAX :- google maps,
7. Gmail, you tube, and facebook.
8. Microsoft and google both corporations played important role in ajax.
Implementation of Ajax can be done in two way in ASP.Net Application

 using Update Panel and,


 using jQuery

Techonologies with AJAX:


 By using jQuery and JSON Web Services, Ajax callbacks have become
standard programming practices for designing and developing web
applications.
  jQuery is used to easily write client-side JavaScript to navigate and
manipulate a page and make asynchronous Ajax callbacks.
 JSON (JavaScript Object Notation) is much easier to use with JavaScript
than XML. When it comes to Ajax and JavaScript, JSON Web Services
are replacing XML Web Services.

2.What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to
accomplish, and wraps them into methods that you can call with a single line of
code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX
calls and DOM manipulation.
The jQuery library contains the following features:

 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities

Tip: In addition, jQuery has plugins for almost any task out there.

Why jQuery?

There are lots of other JavaScript libraries out there, but jQuery is probably the
most popular, and also the most extendable.

Many of the biggest companies on the Web use jQuery, such as:

 Google
 Microsoft
 IBM
 Netflix

 This is to prevent any jQuery code from running before the document is
finished loading (is ready).

 It is good practice to wait for the document to be fully loaded and ready
before working with it. This also allows you to have your JavaScript code
before the body of your document, in the head section.

 All the jquery apply when the document is ready so let the document ready
then the function of jquery will be executed
1. Jquery is the advance library of javascript
2. it is use to provide special extraordinary effects on web application
3. it is open source library so any technology can adopt
4. It provides very light weight code
5. The main advantage it provide better compatibility with ajax
6. It was developed by John resig
7. The first version was launched in 2006
8. The latest version is launched 2019 version is 3.4.1
9. The Jquery is denoted by ($) sign
10. It can be implemented any where but the prefered location or area is
head with the tag of <script></script>
-------------------------------------------------

How to start Jquery

There are two ways to start the jquery with your applicaton

1. Offline

2. By CDN(Content Delivery Network)

Offiline means you can download Jquery file from the official site
WWW.JQuery.com.

The Best CDN provides by Microsoft and Google

-------------------------------------------------

Disadvantages
All the scripts either Jquery or JavaScript are browser dependent so user can stop
the script by browser

Check your system is connected with the internet

3.Accordion
Accordion concept is basically used to utilise the space of the website so the less
space be can display the large number of data in tab manner and we can also close
the tab when there is no requirement .It can be implemented manually as well as
with the help of jQuery library for implementing the JqueryCDN(Content Delivery
Network) is also available.

Widget:-(a user interface component that allows user to perform a function or


access to service)

Accordion is a type ofwidget in jQueryUserInterface that is a jQuery based


expandable and collapsible content holder that isbifergatedinto sections and just
looks like tabs. jQuery User Iinterface provides accordion() method to achieve
thislibrary.

Example:

<script>

$(document).ready(function() {

$("#accordion-1" ).accordion();

});
</script>

//

<div id=”accordion-1”>

<div id=div1>

<h3>Tab 2</h3>

<p>This is the First Tab</p>

</div>

<div id=div2>

<h3>Tab 2</h3>

<p>This is the Second Tab</p>

</div>

<div id=div3>

<h3>Tab 3</h3>

<p>This is the Third Tab</p></div>

</div>

4.AutoComplete
The Auto complete widgets provide suggestions while you type into the
field. In which programmatic some data can be pre stored so when user
will type few character words will be display according to the predefined
or pre stored words list can also be bind from the data base so it enhance
the fast accessing and accuracy Here the suggestions are tags for
programming languages.
<input id="myInput" type="text"
name="myCountry"placeholder="Country">
//In Script tag
<script>
var countries = ["India","America","Japan","China"];
$(“#container”).autocompelete({
Source:countries
});
});
</script>

5. RESIZABLE
 The jQuery UI Resizable plugin makes selected elements resizable,
Means, they have draggable resize handles.
 As per the size of text user can increase or decrease text area. It is
basically used for the space utilization and avoids the proper flexibility,
easily resizable with the help of mouse.
 It Enable any DOM(Document Object Model, all the controls,
interfacing User to manipulate data or manage data) element to be
resizable. With the cursor grab the right or bottom border and drag to
the desired width or height.
 <script>
 $(document).ready(function(){
 $("#container").resizable();
 });
 </script>
 Here, container is the id of tag to which the function of resizable is to
apply.
6. PASSWORD STRENGTH
Password strength means the password should be strong with the
combination of alphabets,digits and special characters and password
length should not be very less,so if any user is typing weak password so
developer can programmatically inform to the user that password should
be strong according to the security compliances.
The following are some of the common properties of the Ajax PasswordStrength
control:

 BarBorderCssClass: Used to set custom css class for border of


PasswordStrength control.

 DisplayPosition: Sets the display position for strength indicator ,default is


right.

 HelpHandleCssClass: Sets the CSS class for help link.

 MinimumLowerCaseCharacters: Defines the how many minimum lower case


letter in password.

 MinimumNumericCharacters: Defines how many numeric characters in


password.

 MinimumSymbolCharacters: Defines minimum occurrences of Special


symbol characters.

 MinimumUpperCaseCharacters: Defines the how many minimum upper case


letter in password.

 PreferredPasswordLength: Defines the length of the password.

6. Calendar Extender
The CalendarExtender is an ASP.NET AJAX control that is associated with a TextBox
control. When the user clicks on the TextBox, a client-side Calendar control pops
up. The user can then set a date by clicking on a day, navigate months by clicking
on the left and right arrow and perform other such actions without a postback.

Calendar extender is a part of ajax control toolkit, so, control toolkit must be on
the webpage. It is not available by default so we need to download from
appropriate site.

>> After downloading how to configure:-

1. Go to toolbox -> Go to ajax extension then right click then add new tab(name
Ajax toolkit)
2. Then right click on Ajax toolkit ->choose item.

Example:-

<script>

    $(function () {

        $("#datepicker").datepicker({
            altField: "#alternate",
            altFormat: "DD, d MM, yy"
        });
    });           
</script>

Description:
Jquery animation() method provide the custom animation with set of CSS
properties.

Syntax
.animate( properties[duration ] [easing ] [complete ] ).animate( properties, options
)

Ex:- $("#div").animate({ });

params parameter defines the CSS properties to be


Params
animated.

 It specifies the speed of the fadein. The valuse may be slow,
fast and milliseconds. (default value: 400). Duration are given
Duration/speed
in milliseconds and higher values indicate slower animations,
not faster ones.

It specifies the easing function to be used for transition


Easing
(default value: swing).

Callback A function to call once the animation is complete.

Example:-

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
 
$(document).ready(function () {
$("#divflipBox").click(function () {
$("#divpanelBox").animate({
height: '+=20px',
width: '+=20px'
});
});
});
 
</script>
7.CAPTCHA- code

A CAPTCHA is a validation layer to recognize the type of user before sending data
to the server.

Advantages of CAPTCHAs

There are many tools to send automated messages. If you have not implemented a
CAPTCHA in your feedback or user registration page then you will get many spam
messages or users.

So the main advantages of CAPTCHA is to avoid spam messages or users.

How to use CAPTCHA in ASP.NET MVC

There are many open-soure libraries available to do this. Even though you can
write your own code to implement a CAPTCHA in your application, that totally
depends on you.

1. using System.Web.Mvc;  
2. using CaptchaMvc.HtmlHelpers;  
3.   
4.   
5. namespace MathCaptcha.Controllers  
6. {  
7.     public class HomeController : Controller  
8.     {  
9.   
10.         public ActionResult Index()  
11.         {  
12.             return View();  
13.         }  
14.   
15.         [HttpPost]  
16.         public ActionResult Index(string empty)  
17.         {  
18.             // Code for validating the CAPTCHA  
19.             if (this.IsCaptchaValid("Captcha is not valid"))  
20.             {  
21.                  
22.                 return RedirectToAction("ThankYouPage");   
23.             }  
24.   
25.             ViewBag.ErrMessage = "Error: captcha is not valid.";  
26.             return View();  
27.         }  
28.   
29.         public ActionResult ThankYouPage()   
30.         {  
31.             return View();  
32.         }  
33.   
34.     }  
35. } 

UNIT -2
1. Web Development
Web development broadly refers to the tasks associated with developing websites
for hosting via intranet or internet. The web development process includes web
design, web content development, client-side/server-side scripting and network
security configuration, among other tasks.
Web development is the coding or programming that enables website
functionality, per the owner's requirements. It mainly deals with the non-design
aspect of building websites, which includes coding and writing markup.
Web development ranges from creating plain text pages to complex web-based
applications, social network applications and electronic business applications.
The web development hierarchy is as follows:

 Client-side coding
 Server-side coding
 Database technology

2. ASP.NET MVC advantages and disadvantages

3. ASP.NET Web Forms and MVC are two web frameworks developed by
Microsoft. ASP.NET MVC is not replacing ASP.NET WebForms. Both
these development models exist and can be used to develop ASP.NET
applications

But it is very much essential to understand the different between these two

What are the main Advantage of ASP.NET MVC over ASP.NET


Advantages of MVC
One of the main benefits of using MVC is its support for testability that enables
the Test Driven Development approach in a simple way. An application must be
created in a loosely coupled way to make it testable. Such an application allows
easy testing of different application parts. The framework support is extremely
important to create the testable applications. In fact, testing was a major design
goal of MVC.
1) Faster development process: MVC supports rapid and parallel development.
With MVC, one programmer can work on the view while other can work on the
controller to create business logic of the web application. The application
developed using MVC can be three times faster than application developed using
other development patterns.
2) Ability to provide multiple views: In the MVC Model, you can create multiple
views for a model. Code duplication is very limited in MVC because it separates
data and business logic from the display.
3) Support for asynchronous technique: MVC also supports asynchronous
technique, which helps developers to develop an application that loads very fast.
4) Modification does not affect the entire model: Modification does not affect the
entire model because model part does not depend on the views part. Therefore,
any changes in the Model will not affect the entire architecture.
5) MVC model returns the data without formatting: MVC pattern returns data
without applying any formatting so the same components can be used and called
for use with any interface.
6) SEO friendly Development platform: Using this platform, it is very easy to
develop SEO-friendly URLs to generate more visits from a specific application.
7) Provides clean separation of concerns(SoC).
8) Easy integration with JavaScript frameworks.
9) Enables the full control over the rendered HTML.
10) No ViewState and PostBack events
11) MVC provides better [TDD] Test Driven Development this approach is better
for software testing
Test-driven development (TDD) is a software development process that relies on
the repetition of a very short development cycle: requirements are turned into
very specific test cases, then the software is improved to pass the new tests, only.
This is opposed to software development that allows software to be added that is
not proven to meet requirements.
Disadvantages of MVC
f1) Increased complexitys\
2) Inefficiency of data access in view
3) Difficulty of using MVC with modern user interface.
4) Need multiple programmers
5) Knowledge on multiple technologies is required.
6) Developer have knowledge of client side code and html code.

3. Difference Between ASP.NET Web forms and ASP.NET MVC

ASP.NET Web Forms ASP.NET MVC


ASP.NET web forms have the server Asp.net mvc has html controls and
controls html helpers
No separation of concern every page Very clean Separation of concern
has its own controller so they are approach is there means a common
tightly coupled, i.e code behind file controller can process the request of
that process the request multiple pages(View). View and
controller are smartly separated
 Asp.Net Web Form has Master  Asp.Net MVC has Layouts for
Pages for consistent look and feels. consistent look and feels.

 In Asp.Net Web Form, views are In Asp.Net MVC, Views and logic
tightly coupled to Code are kept separately.
behind(ASPX.CS) 
 Because of this coupled  Testing can be done very easily
behavior, automated testing is really in MVC environment. Testability is
difficult the key feature in Asp.net Mvc. Test
driven development is quite simple.
 Less Knowledge of HTML, CSS  Full control and knowledge
and java script is required
 Asp.Net Web Form has built-in  Asp.net MVC provides the light
data controls and best for rapid weighted code it follow the latest
development with powerful data web standards for developing the
access. web pages

 Asp.Net Web Form has state  Asp.Net MVC has no automatic
management (like as view state, state management techniques.
session) techniques. 

ASP.NET web forms use page  In MVC multiple views can be
controller pattern approach in this created under on controller this
approach every page has its own approach is called
controller i.e code behind file the  Front Controller approach
process the request
 ASP.NET has view state  MVC doest not as view state
 In Asp.net we can see the  But its not possible without
layout of page parallel without running the page we cannot the
running the page exact display of page
4. Merits of MVC over .NET

 MVC is lightweight as compare to Asp.net and follow MVC model


 (Model, View, Controller) pattern based development model that
hold separation of concerns where view and logic are kept
separately that supports effective enhancement and deployment.

 It provides view engines which helps in mark up syntax that


facilitate to embed server base code into web pages due to which
load on server is less.

 It is more secure than ASP.net technology that lets down the cross
scripting done by impostor.

 In MVC it supports multiple views in one controller.


MVC provide full control over mark up and support many features
that allow fast &amp; agile development.
 MVC also provide Scaffolding technique that generate code for
CRUD operations, which saves time as compare to ASP.NET
 MVC provides route based URL technique which holds easy and
 secure traversing.
 No page life cycle is stand in MVC due to which the deployment is
 fast.
 It also provides filter technique which keep application data
 integrity.
IMPORTANT POINTS OF MVC

1. Asp.net mvc has derived from the features of MVC


2. MVC is a design pattern
3. MVC is use for developing web based application, mobile based application,
desktop based application
4. MVC is used by all the technologies like ASP, JAVA, PHP

What every you write in the form of html it can only display on browser
So if we are using some c# code then view engine convert these code into
html format then these code display on browser

To cancel the effect of @ we can use two @@


@anees.itlucknow INVLAID

5.MVC Architecture
The MVC Architecture is existing in software engineering from the long time.
Mostly all the language presently using MVC.  MVC is a popular way of organizing
your code

MVC stands for Model, View and Controller. MVC separates application into three
components - Model, View and Controller.

Any software or application is divided into three part User Interface by which user
interact to the application and flow of control and logic and the storage
Model

1. It is a data and business logic


2. It maintain the data of the application
3. It provide the mechanism to store the data and retrieve the data whenever it
is required
4. It is the essential component of the application
5. Model provides the source of data that manage and control by controller and
display on view
6. Data can be store in the file or huge data store in Data base management
systems
7. Model respond to controller when any request comes from controller end
8. Model View Controller is a design approach to separate the application
object model from GUI, in which all the data related logic are kept. This can
represent either the data that is transferred between the view and the
controller or any other business logic. Database related all the operation are
performed in this segment
9. For example Student Object will access the student information from the
data base manipulate it and store back the database.

View
1. View is the user interface
2. User interact with the help of View
3. It provides all the thing that user can see and respond, like button , check
boxes ,
menus etc
4. View component is used for all the UI logic of the application and these are
the components that display the application’s user interface (UI)
5. View only interact with the controller not with model whenever any event
occur it send to controller
6. The View is the component in which user interact with application it is a user
interface all the designing which is required for the application are place in
View all kind of component such as textboxes, dropdown list, radiobutton,
checkboxes are placed in View

Controller

1. Controller handles user's requests and renders appropriate View with Model
data.
2. Controllers act as an interface between Model and View components.
3. Controller co-ordinate with model and view both
4. 4. Controller is responsible for all the programmatic logic of application. It act
as n interface between model and view components to process all the
business logic and incoming requests
<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Index</title>

</head>

<body>

<div>

<h2>This is the first view in MVC</h2>

<hr />

@{

<span style="color:red; font-size:20px;">The factorial is


@ViewBag.res</span>

<br />

<span>The value @ViewData["value"]</span>


}

</div>

</body>

</html>

Controller

//string n = "National PG college";

//ViewBag.result = n;

int n = 5, i, f = 1;

for (i = 1; i <= n; i++)

f = f * i;

ViewBag.res = f;
int num = 124;

ViewData["value"] = num;

return View();

For HyperLinking

<a href="/Home/process"> To Move On Process </a>

Important Statement For Sending the Data to Controller

<form method="post" action="/Home/Index">

Button Important Properties

<input type="submit" name="btn" value="Generate Table" />

1. name means this name will be participate in coading


2. value it will display on button
3. type must be submit otherwise from will not be submit on controller

@{
if(IsPost)

int i,n;

n=int.Parse(ViewBag.num);

for(i=1;i<=10;i++)

<span style="font-size:20px;">@(i*n)</span><br />

<br />

The default name of controller is Home

The default name of View is index

We can change the defualt names of controller and view in Route config file which
is created inside MVC architecture

_________________________________________________________
M model

V view

C controller

__________________________________________________________

Before start work in MVC we have to add controller first of all

controller controls the view as well as model

6.MVC Scaffolding
It provides readymade code for CRUD operation on the basic of entity frame works
internally it is technique to create the automatic codes for data base operations.
MVC scaffolding use in rare cases because it generate the automatic code and
some time these codes not matched with the architecture of project. For fast and
quick demonstration it is ok it is mainly used for presentation purpose suppose we
want to provide quick presentation and donot want to involve any external data
base technique but for professional and enterprise project it is not used.

Some time generated code is not completely understand by the programmer.

It is nothing but an technique which provide the

Step1
Create a class in model with property getter setter and also define a key(as primary
key) and key is generated by key attribute and key attribute is available in

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations;

This namespace use to may any data member as primary key

namespace scaff1.Models

public class Emp

[Key]

public int empid { get; set;}

public string Name { get; set;}

public int Age { get; set;}

public int Salary { get; set;}

}
Step2

Build solution using Build solution option in Build menu

Step 3

1. Add Controller (Name Home)

2. Choose Template (MVC controller with read/write action and view using
Entity Frame work)

3. Model Class (Actual (c#)Class which we have already created in step 1)

4. Data context Class (This class represent the data base in Entity frame work
EmpDB)

5. View (Razor)

6. Advance (Unchecked layout master page)

7. Add

8. Run Project

Note: If we do any kind of changes in the class then we have to rebuild the
solution its very important

Table will be created in data connection we can expand and see simply
Meaning of Scaffolding

A temporary structure on the outside of a building, made of wooden planks and


metal poles, used by workmen while building, repairing, or cleaning the building.

UNIT – 3

1. View Engine(aspx and razor view engine)

Before stating the description of View Engine. We discuss one thing that is suppose
we create any web form related to HTML TAGS. That web page will be treated as
static but suppose we want to add some c# or any other programming language
codes in between HTML so it is not possible. So View Engines provides the facility
to mix HTML and Programming Codes.

So in Asp.net we have the two options regarding the View Engine

1. ASPX View Engine or Web Form View Engine (Old)


2. Razor View Engine. (Latest)
Note: Some third party View Engine (like Spark , Nhaml, Brail, SharpTiles, Hasic
and many more) support is also available in ASP.NET we give the preference to
default Veiw Engine of ASP.NET

Difference between ASPX View Engine and Razor View Engine

s.no Razor View Engine ASPX or Web Form View Engine


1 It is advance view engine It is the default View Engine for Asp.net
that was introduce with MVC and it is included from the
MVC3 beginning.
2 The name space for the The name space for the Aspx View
Razor View Engine is Engine is
System.Web.Razor System.Web.Mvc.WebFormViewEngine
3 The extension of Razor The extension of Aspx View Engine is
View Engine is .cshtml .aspx
(Razor with c#)
4 Razor has new and Comparatively ASPX View Engine Code
advance syntax which is is complicated
easy to understand and
usable and provide very
clear view and reduce
typing.
5 Razor use @ symbol to Aspx View Engine use <% and %>
make the code
For Eg @{ For Eg <%:
int int a=2,b=4,c=0;
a=2,b=4,c=0; c=a+b;
c=a+b; %>
}
6 Razor does not support While Aspx support the design mode in
design mode in visual visual studio we can see the design
studio mean we cannot without running application.
see the design without
running the application.
7 Razor View is little bit Comparatively faster
slow in comparison of
Aspx View
8 Razor View Engine Aspx View Engine does not prevent
prevent Cross Site
Scripting Attacks means
it encodes the script or
html tags before
rendering to view
9 Razor Engine Support Aspx doesn’t support Test Driven
Test Driven Deployment Deployment

10 The Razor View Engine is Not very much compatible with the unit
compatible with a unit testing
testing framework
11 Razor also supports the Aspx support the concept of Master
concept of layout pages Page

Advantages of Razor View Engine

1. It is easy to use and implement


2. Razor helps us to minimize the coding and provide us a fast and fluid coding
work flow.
3. Powerful built-in validation of markup that helps us to avoid unwanted
runtime exceptions due to errors in the view.
4. The code looks clean.
5. Razor does not require any special tool to write markup. We can also write
our markup code with any old plain text editor like Notepad.
6. The @model directive provides a cleaner and more concise way to define a
strongly typed model
7. Improves readability of the markup and code

Razor Code Syntax

1. Razor Expression
These are single Line C# Statement
@Statements

2. Razor Block
These are multiline Statement
@
{
Statements
}

Note: So due to these Razor engine is capable to identify which is HTML code and
What are c# codes

Request object

How to access the View data without transfer into the controller using Request
object
View coading

@{

Layout = null;

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Index</title>

</head>

<body>

<div>

<h1>Data Manupulation in View</h1>

<hr />

<form action="/" method="post">

<table>

<tr>
<td>Enter Student Name</td>

<td><input type="text" name="txtname" /></td>

</tr>

<tr>

<td>Enter First sub marks </td>

<td><input type="number" name="s1" /></td>

</tr>

<tr>

<td>Enter Second sub marks </td>

<td><input type="number" name="s2" /></td>

</tr>

<tr>

<td>Enter Third sub marks</td>

<td><input type="number" name="s3" /></td>

</tr>

<tr>

<td><input type="submit" name="Calculation" /></td>

</tr>
</table>

@{

if(IsPost==true)

double a, b, c, sum, avg;

a = double.Parse(Request["s1"]);

b = double.Parse(Request["s2"]);

c=double.Parse(Request["s3"]);

sum = a + b + c;

avg = sum / 3.0;

<br />

<br />

<h4>Result</h4>

<hr />

<span style="color:red; font-size:20px">Name =


@Request["txtname"]</span> <br />

<span style="color:red; font-size:20px">Sum = @sum</span> <br />

<span style="color:red; font-size:20px">Average = @avg</span> <br />


}

</form>

</div>

</body>

</html>

Now we have to transfer the data to controller and do all the processing of data
to the controller and then transfer the result into the controller

1. By control
2. By FromCollection
3. By Model

Same example using by control Method

public ActionResult Index()

Response.Write("<script> alert('Get method called')</script>");

return View();
}

[HttpPost]

public ActionResult Index(string txtname,string s1, string s2, string s3)

double a, b, c, sum, avg;

a = double.Parse(s1);

b = double.Parse(s2);

c = double.Parse(s3);

sum = a + b + c;

avg = sum / 3.0;

Response.Write("Average is " + avg);

ViewBag.name = txtname;

ViewBag.sum = sum;

ViewBag.average = avg;

return View();

}
REQUEST OBJECT WITH DIFFERENT PAGE

@{

Layout = null;

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Index</title>

<style>

body {

background-color:lavender;

a{

text-decoration:none;

</style>
</head>

<body>

<div>

<h1>First view in MVC</h1>

<hr />

<a href="/Home/SecondView">Click Here To Move On Second View</a>

<form method="post" action="/Home/SecondView">

<table>

<tr>

<td>Enter Principal</td>

<td><input type="text" name="t1" /></td>

</tr>

<tr>

<td>Enter Rate </td>

<td><input type="text" name="t2" /></td>

</tr>

<tr>

<td>Enter Time</td>

<td><input type="text" name="t3" /></td>


</tr>

<tr>

<td><input type="submit" value="Submit" /></td>

</tr>

</table>

</form>

@{

if(IsPost)

int a, b, c, sum = 0;

a = int.Parse(Request["t1"]);

b = int.Parse(Request["t2"]);

c = int.Parse(Request["t3"]);

sum = a + b + c;

<br /><br />

<span>Result @sum</span>

}
</div>

</body>

</html>

@{

Layout = null;

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>SecondView</title>

</head>

<body style="background-color:lightgreen">

<div>

<h2>This is the Second View</h2>


<hr />

@{

int a, b, c, sum = 0;

a = int.Parse(Request["t1"]);

b = int.Parse(Request["t2"]);

c = int.Parse(Request["t3"]);

sum = a + b + c;

<span>Result @sum</span>

</div>

</body>

</html>

namespace MvcApplication3.Controllers

public class HomeController : Controller

//
// GET: /Home/

public ActionResult Index()

return View();

public ActionResult SecondView()

return View();

2.Session In Asp.net Mvc


As we know that web is stateless. So every time when page gets loaded new
instances is used to create it. There are many way to store the data for future
usage. So data generally processed in the controller for security reasons so for
transfer the data from controller to view MVC provides three ways

1. ViewBag
2. ViewData
3. TempData

 ViewBag and ViewData are almost same but TempData perform some more
responsibilities

 ViewBag and ViewData Helps to maintain the data when we move from
controller to view without the above session it is not possible to display the
processed data by controller to view.

 Both have the short life mean values become destroy or null when
redirection occurs. After communication with view values become empty.

 ViewData is a dictionary of object that is derived from ViewDataDictionary


Class and is accessible by string key

 All dictionary object access on the basis of key

 ViewData Requires typecasting for complex data type and checks for null
values to avoid error. Without typecasting the data cannot be retrieved
which is stored in the ViewData

 ViewData's life only lasts during current http request. ViewData values will be
cleared if redirection occurs.

ViewBag

1. ViewBag only transfers data from controller to view, not visa-versa. ViewBag
values will be null if redirection occurs.
2. ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0
3. ViewBag doesn’t require typecasting for complex data type. Without
typecasting data can be retrieved and display on view
4. We can assign any number of properties and values to ViewBag

TempData

1. It helps to maintain data when you move from one controller to other
controller or from one action to other action. In other words, when you
redirect, “Tempdata” helps to maintain data between those redirects. It
internally uses session variables.

2. It requires typecasting for complex data type and checks for null values to
avoid error. Generally, it is used to store only one time messages like the
error messages and validation messages

3. TempData is useful when you want to transfer data from one action method
to another action method of the same or a different controller as well as
redirects. It is dictionary type which is derived from TempDataDictionary

TempData.Keep(key: "result3"); Use to persist data then only data can move
from one controller to another controller or another action method

Example of ViewBag, ViewData, TempData

View

<div>

<h2>Data Display using View Bag</h2>


<ul>

@{

foreach(string n in ViewBag.res)

<li style="font-weight:bold;color:red;font-size:20px;">@n</li>

</ul>

<hr />

<h2>Data Display using View Data</h2>

<ol>

@{

foreach(string n in ViewData["stu"] as List<string>)

<li style="color:blue; font-weight:bold; font-size:20px;">@n</li>

}
</ol>

<hr />

<h2>Data Display Using Temp Data</h2>

<ol>

@{

foreach(string n in TempData["tstu"] as List<string>)

<li style="color:maroon;font-size:20px;font-weight:bold;">@n</li>

</div>

Controller

public class HomeController : Controller

//

// GET: /Home/
public ActionResult Index()

List<string> student = new List<string>();

student.Add("Mahira");

student.Add("Anees");

student.Add("Mahi");

student.Add("Seemab");

student.Add("Rizwan");

ViewBag.res = student;

//-------------------------------

ViewData["stu"] = student;

//--------------------------------

TempData["tstu"] = student;

return View();

}
3.Routing in Asp.Net MVC

Browsers Generates the requests

[Chrome, Mozilafire fox , Internet


Exprlorer]

All request accept by Controller


and controller interact with view
and model accordingly controller
respond

View Model

1. Routing is the pattern matching system


2. Routing map incoming request(from browser) to a particular controller and
action method
3. This url match in the route table then url processed
4. All the route are stored in routing table
5. RouteTable is a collection of routes that is stored in RouteConfig.cs file in
App_Start folder of the application.
6. When a MVC application first starts, the application _start() method is called
which is in Global.asax. This method in turn calls RegisterRoutes() method
which creates Route table.

Example http://localhost:15556/Home/Index

15556 is the server on which application is hosted it may be local server or any
remote server after that home is the default controller and index is the default
view [Home and Index is also called path segment] here home is mapped with the
controller class and index is mapped with index action method

These mapping is done by the routing rules define in our application we can create
new routes as well as we can change the default routes as per requirement
Routing

Routing is a mechanism which is define that what action method is executes into
controller class. Routing is a pattern matching system that monitors or checks the
incoming request and takes the appropriate decisions what to do with that
request. At runtime, Routing engine use the Route table for matching the incoming
request's URL pattern against the URL patterns defined in the Route table. All the
configured routes of an application stored in RouteTable and will be used by
routing engine to determine appropriate handler class.

When the routing engine finds a match in the route table for the incoming
request's URL, it forwards the request to the appropriate controller and action

Inside App_start there is a file called RouteConfig.cs which is use to define the
multiple routes it has a single method RegisterRoute and also contain the default
Routing configuration with some Default property

Url Patterns means what exactly the way to action which controller and which
action method
1. {controller}/{Action}
2. Home/Index
3. {Controller}/{Action}/{ID} Note : ID is optional

Url Pattern can be customize when we define our own routes

=>into the ControllerClass we can define two types of method : -

1)ActionMethod

2)Non-ActionMethod

We can also configure the multiple Route in a single application as per need of
Application so configuration of multiple route we have to create the new route in
RouteConfig.cs

User Define Route only Change the action

routes.MapRoute(

name: "Route2",

url: "R1/",
defaults: new { controller = "Home", action = "index2", id =
UrlParameter.Optional }

);

User Define Route change the controller and Action Method

routes.MapRoute(

name: "SR2",

url: "SR1/",

defaults: new { controller = "Second", action = "Index", id =


UrlParameter.Optional }

);

Default Route

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }

);

Note : In all above Routes the id is optional either we give in the url or not it will
work it is use to access the particular record or some particular data

Explain the concept of load balancing using different route of same home and
action method

routes.MapRoute(

name: "Route2",

url: "R2",

defaults: new { controller = "Home", action = "Index2", id =


UrlParameter.Optional }

);

routes.MapRoute(

name: "Route3",

url: "R3",
defaults: new { controller = "Home", action = "Index2", id =
UrlParameter.Optional }

);

So we get the same page by R2 or R3

UNIT – 4

1. JSON
Ajax Implementation Using JSON and Jquery

Traditional web applications rely on synchronous method calls to process data.


The entire web page is posted to the server each time data is submitted through
the page, causing performance delays.

This problem can be overcome by using AJAX. AJAX allows web applications to call
methods asynchronously. Instead of posting the entire page to the web server,
only the required data is posted. This improves the overall performance of the
web applications.

As we all know, AJAX means Asynchronous JavaScript and XML. It is a client-side


script that communicates to and from a server/database without the need for a
postback or a complete page refresh. The Ajax speeds up response time.
Implementation of Ajax can be done in two way in ASP.Net Application

 using Update Panel and,


 using jQuery

JSON[ Java Script Object Notation]

What is the use of Json ?

JSON is very commonly used concept in MVC and other technology. It is a data
interchange medium and a very light weighted code between client and server. It
is language independent so any technology and language can use the concept of
JSON. It is mainly use when AJAX call and functionality implement in project so it
provide the partial rendering without refreshing the entire heavy page of web
page it can transfer the data to server as well it can receive the data from server.

JsonResult is actually a special ActionResult , which suggest the View Engine that
the object of JSON type will be returned rather than normal HTML

1. JSON objects are surrounded by curly braces {}.

2. JSON objects are written in key/value pairs.

3. Keys and values are separated by a colon.


Uses of JSON
 It is used while writing JavaScript based applications that includes browser
extensions and websites.
 JSON format is used for serializing and transmitting structured data over
network connection.
 It is primarily used to transmit data between a server and web applications.
 Web services and APIs use JSON format to provide public data.
 It can be used with modern programming languages.
Characteristics of JSON

 JSON is easy to read and write.


 It is a lightweight text-based interchange format.
 JSON is language independent.

$(document).ready(function () {

jsonobj = { "name": "Raman", "Age": "24", "Marks": "90" };

var res = "";

res += "Name " + jsonobj.name + "<br>";

res += "Age " + jsonobj.Age + "<br>";

res += "Marks " + jsonobj.Marks;


$("#div1").html(res); });

___________________________________________________________________
______________

JSON OBJECT AS ARRAY

jsonobj = [{ "Name": "Mahira", "Age": "24", "City": "Mumbai" }, { "Name": "Raj",


"Age": "34", "City": "Lucknow" }];

for(i=0;i<=1;i++)

res += jsonobj[i].Name + "<br>";

res += jsonobj[i].Age + "</br>";

res += jsonobj[i].City + "</br>";

res += "______________________________</br>";

$("#div1").html(res);
jsonobj = [{ "name": "Raman", "Age": "24", "Marks": "90" }, { "name": "Ram",
"Age": "30", "Marks": "95" }];

var res = "";

for (i = 0; i < jsonobj.length; i++)

res+=(jsonobj[i].name + " " + jsonobj[i].Age + " " +


jsonobj[i].Marks+"<br>");

$("#div1").html(res);

View Coading

$.getJSON("/Admin/GetAttendence", {Rn:rollno,Atten:attendance}, function (msg)


{

if (msg == "success")

alert("saved records");

})
Controller Method

public ActionResult GetAttendence(string Rn, string Atten)

string msg = "success";

return Json(msg, JsonRequestBehavior.AllowGet);

//return View();

Insertion and searching Using Json Ajax implementation with page refresh

While creating the function related to Json make sure post function should not
be created

$(document).ready(function () {

$("#btn").click(function () {

var name, marks;

nam = $("#name").val();

marks = $("#marks").val();
$.getJSON("/Home/insertion", { n: nam, m: marks }, function (msg)
{

if (msg == "success") {

alert('Record Inserted');

else

alert('Record not inserted');

});

Controller part coading

public ActionResult insertion(string n,string m)

int marks = int.Parse(m);

string msg;

string q = "insert into tbl_student values('" + n + "','" + marks + "')";

bool j = dm.insertupdatedelete(q);

if (j == true)

msg = "success";
else

msg="failure";

return (Json(msg, JsonRequestBehavior.AllowGet));

Search Record

$("#searchbtn").click(function () {

var ssid = $("#sid").val();

$.getJSON("/Home/search", { searchid: ssid }, function (msg) {

if (msg == "find") {

$("#span1").html("Record Found Successfully");

else {

$("#span1").html("Record Not Found Successfully");


}

});

});
Controller part coading for search

public ActionResult search(string searchid)

int id = int.Parse(searchid);

string msg;

string q="select * from tbl_student where studentid='"+id+"'";

DataTable dt = dm.readbulkdata(q);

if (dt.Rows.Count > 0)

msg = "find";

else

msg = "not found";

return (Json(msg, JsonRequestBehavior.AllowGet));

2.BUNDLING AND MINIFICATION

Bundling and minification techniques were introduced in MVC 4 to improve


request load time. Bundling allow us to load the bunch of static files from the
server into one http request.
Advantage of BUNDLING and MINIFICAITON

1. It improves the web page load time.


2. This is the performance optimization technique

Suppose in a particular web page 25 css and 30 Java Script files so total 55 files are
there so for load complete web page browser required 55 http load request.
Bundle compress or combine the multiple file in single file so single file can be
download in single request

Minification reduces the file size so overall load of the website will be reducing. So
how the file in minimize in minificaiton process it removes the comment, Remove
white spaces, Shorten Variable name so after doing these sort of minification we
received the minified version of java script and css files

Jscompressor.com

Bundle Types:
MVC 5 includes following bundle classes in System.web.Optimization namespace:

ScriptBundle: ScriptBundle is responsible for JavaScript minification of single or


multiple script files.
StyleBundle: StyleBundle is responsible for CSS minification of single or multiple
style sheet files.

DynamicFolderBundle: Represents a Bundle object that ASP.NET creates from a


folder that contains files of the same type.

All the above bundle classes are included


in System.Web.Optimization.Bundle namespace and derived from Bundle class.

Points to Remember :

1. Bundling and Minification minimize static script or css files loading time
therby minimize page loading time.
2. MVC framework provides ScriptBundle, StyleBundle and
DynamicFolderBundle classes.
3. ScriptBundle does minification of JavaScript files.
4. StyleBundle does minification of CSS files.
Minification techniques were introduced in MVC 4 to improve request load time.
Bundling allow us to load the bunch of static files from the server into one http
request.

MINIFICATION

1. It improves the web page load time.


2. This is the performance optimization technique
3. MVC framework provides ScriptBundle, StyleBundle and
DynamicFolderBundle classes.
4. ScriptBundle does minification of JavaScript files.
5. StyleBundle does minification of CSS files.

Minification reduces the file size so overall load of the website will be reducing. So
how the file in minimize in minificaiton process it removes the comment, Remove
white spaces, Shorten Variable name so after doing these sort of minification we
received the minified version of java script and css files. After making the javascript
or css file we can minified these file so the overall size will be reduce and
performance of the website will be increase minification can be done online most
of the site are available for minfication process we only have to put the complete
java script file and online site will produce the minified form of the java script file
and then we can use the minified files for example JSCOMPRESSOR

3.Entity Framework
it is an open source ORM(Object Relational mapper) Framework developed by
MicroSoft .EntityFramework is also used internal ADO.Net .

Object Relational Mapping framework automatically creates classes based on


database tables. It can also automatically generate necessary SQL to create
database tables based on classes

=>How we can performs CRUD Operation By Using EF .

-----------------------------------------------------

1)Features of EF :-

1) Configuration

-----------------------

Any kind of configuration is not required, automatic it establish the connection


string with database

2) Command

---------------

Command is not required

3) Object oriented approach

-------------------------------------

Every table or data base represent in the form of class.


Important method for CRUD operation

------------------------------------

1. for insertion

Add(above 4.0) or AddObject (below 4.0)

2. For save the record

SaveChanges(Object of Table)

Important Steps of storing record in database using EFWORK

1. Entity Frame model creation save and rebuild


2. Add Controller
3. Using name space <ProjectName>.models
4. Create the object
ENTITYDATABASEEntities db = new ENTITYDATABASEEntities();
5. Create post index method with parameter(TBL_emp emp)
6. db.TBL_EMP.Add(emp);
7. db.SaveChanges(); //commit records permanent storage
8. response.redirect(“/home/index”); without refresh record will be display on
the screen.
Display Record using Dynamic table
1. if you want to display records on view of html
2. Bind table records with List
List<TBL_EMP> lst = db.TBL_EMP.ToList();
3. Create a table header
string table = "<table border='1' cellpadding='10' cellspacing='10'
style='color:red'><tr><th>Employee Id</th><th>Employee
Name</th><th>Employee City</th><th>Employee Age</th><th>Employee
Salary</tr>";
4. Execute a Loop
5. for (int i = 0; i < lst.Count; i++)
6. table+="<tr><td>"+lst[i].EMP_ID+"</td><td>"+lst[i].EMP_NAME+"</td><td>"
+lst[i].EMP_CITY+"</td><td>"+lst[i].EMP_AGE+"</td><td>"+lst[i].EMP_SALA
RY+"</td></tr>";
7. Store dynamic table in ViewBag
ViewBag.tbl = table;

8. Now use Razor Block in View


@{

if(ViewBag.tbl!="")

@Html.Raw(ViewBag.tbl);

 Deletion
public ActionResult Delete()

{
int id = int.Parse(Request.QueryString["empid"].ToString());

//var del = new TBL_EMP { EMP_ID = id };

// db.TBL_EMP.Attach(del);

TBL_EMP emp = db.TBL_EMP.SingleOrDefault(a => a.EMP_ID == id);

db.TBL_EMP.Remove(emp);

db.SaveChanges();

Response.Write("<script>alert('Record deleted ')</script>");

Response.Redirect("/Home/Index");

return View();

Index Coading

public ActionResult Index()

List<TBL_EMP> Lst = db.TBL_EMP.ToList();

string table = "<table><tr style='background:orange;color:white;font-


size:20px;text-align:center;font-weight:bold;'><th>Emplyee Id</th><th>Emplyee
Name</th><th>Emplyee City</th><th>Emplyee
Age</th><th>Salary</th><th>Delete</th><th>Update</th><th>Details</th></tr>"
;

for (int i = 0; i < Lst.Count; i++)

{
table += "<tr style='background:red;color:white;font-size:20px;text-
align:center;font-weight:bold;'><td>" + Lst[i].EMP_ID + "</td><td>" +
Lst[i].EMP_NAME + "</td><td>" + Lst[i].EMP_CITY + "</td><td>" + Lst[i].EMP_AGE
+ "</td><td>" + Lst[i].EMP_SALARY + "</td><td><a href='/Home/Delete?empid="
+ Lst[i].EMP_ID + "'>Delete</a></td><td><a href='#'>Update</a></td><td><a
href='/Home/Details?dt="+Lst[i].EMP_ID+"'>Details</a></td></tr>";

table += "</table>";

ViewBag.tab = table;

return View();

 Details
public ActionResult Details()

int id = int.Parse(Request.QueryString["dt"].ToString());

TBL_EMP emp = db.TBL_EMP.SingleOrDefault(a => a.EMP_ID == id);

return View(emp);

Veiw of Details

@{
Layout = null;

<!DOCTYPE html>

@using ENTITYFRAMEWORKDEMO.Models

@model TBL_EMP

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Details</title>

</head>

<body>

<div>

<table>

<tr>

<td>Employee Name</td>

<td>

<input type="text" value="@Model.EMP_NAME" readonly="true"/>

</td>
<td>Emplyee City</td>

<td>

<input type="text" value="@Model.EMP_CITY" />

</td>

<td>Employee Age</td>

<td>

<input type="text" value="@Model.EMP_AGE" />

</td>

<td>Salary</td>

<td>

<input type="text" value="@Model.EMP_SALARY" />

</td>

</tr>

</table>

</div>

</body>

</html>
Entity Frame work

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ENTITYFRAMEWORKDEMO.Models;

namespace ENTITYFRAMEWORKDEMO.Controllers

public class HomeController : Controller

//

// GET: /Home/

//create DataBase Object as Global

ENTITYDATABASEEntities db = new ENTITYDATABASEEntities();

public ActionResult Index()

List<TBL_EMP> Lst = db.TBL_EMP.ToList();


string table = "<table><tr style='background:orange;color:white;font-
size:20px;text-align:center;font-weight:bold;'><th>Emplyee Id</th><th>Emplyee
Name</th><th>Emplyee City</th><th>Emplyee
Age</th><th>Salary</th><th>Delete</th><th>Update</th><th>Details</th></tr>"
;

for (int i = 0; i < Lst.Count; i++)

table += "<tr style='background:red;color:white;font-size:20px;text-


align:center;font-weight:bold;'><td>" + Lst[i].EMP_ID + "</td><td>" +
Lst[i].EMP_NAME + "</td><td>" + Lst[i].EMP_CITY + "</td><td>" + Lst[i].EMP_AGE
+ "</td><td>" + Lst[i].EMP_SALARY + "</td><td><a href='/Home/Delete?
empid="+Lst[i].EMP_ID+"'>Delete</a></td><td><a
href='#'>Update</a></td><td><a href='#'>Details</a></td></tr>";

table += "</table>";

ViewBag.tab = table;

return View();

[HttpPost]

public ActionResult Index(TBL_EMP emp)

db.TBL_EMP.Add(emp);

db.SaveChanges();
Response.Write("<script>alert('Records saved into database ');</script>");

Response.Redirect("/Home/Index");

return View();

public ActionResult Delete()

int id = int.Parse(Request.QueryString["empid"].ToString());

var del = new TBL_EMP { EMP_ID = id };

db.TBL_EMP.Attach(del);

db.TBL_EMP.Remove(del);

db.SaveChanges();

Response.Write("<script>alert('Record deleted ')</script>");

Response.Redirect("/Home/Index");

return View();

View code
@{

if(ViewBag.tab!="")

@Html.Raw(ViewBag.tab )

<col width='130'><col width='130'>

4.Filters

Filters are basically use to perform any logic before or after an action method is
being called so according to the need of project a single or multiple filters can be
applied in a controller. There is a provision of built-in filter and custom filters in
MVC.

Filter general meaning though which something has to pass before


actual processing take place it change the flow of execution.

List of common Built-in Action Filters

S.no Name of Filter Purpose


1. OutputCache It will cache the last state and
proceed according to the
condition specified in
outputcache
2. Authorize Only authorized user will access
the action method no anonymous
user are permitted
3. ValidateInput Turn on or off request validation
4. ValidateAntiForgeryToken Help to prevent the cross site
request forgeries.
5. HandleError Using in Excepiton handling cases

Example of OutputCache Action Filter

[OutputCache(Duration=15)]

public ActionResult Index()

string dt = DateTime.Now.ToLongTimeString();

ViewBag.dtime = dt;

return View();

Example of OutputCache Authorize Filter

[Authorize]

public ActionResult Process()

return View();

}
For understanding the concept of validate input one thing very important that tags
cannot be submit in the form due to high security reasons because due to tags
some unauthorized data can be access using script tags by default validate input is
true

But manually it can be set as false.

Example of OutputCache ValidateInputFilter

[HttpPost]

[ValidateInput(false)]

public ActionResult Process(string txtname)

ViewBag.result = txtname;

return View();

Very Important ActionFilter


Some illegal user can copy the code from one site and paste or integrate the
code in their site and can submit the data in my site so we can prevent this kind
of copied by ValidateAntiForgeryToken

STEAL CODE

<form action="http://localhost:1336/Home/Process" method="post">

Enter Project Name <input type="text" name="txtname" />

<input type="submit" id="btn" value="submit" />

</form>

So it a two step process to prevent

Step1

[HttpPost]

[ValidateInput(false)]

[ValidateAntiForgeryToken()]

public ActionResult Process(string txtname)

ViewBag.result = txtname;

return View();

}
Step2

<form action="/Home/Process" method="post">

@Html.AntiForgeryToken();

Enter Project Name <input type="text" name="txtname" />

<input type="submit" id="btn" value="submit" />

</form>

5.HTML HELPER CLASSES IN ASP.NET MVC

We can build an ASP.NET MVC application without using them, but HTML Helpers
helps in the rapid development of a view. HTML Helpers are more lightweight as
compared to ASP.NET Web Form controls as they do not use ViewState and do not
have event models.

In ASP.Net web forms, developers are using the


toolbox for adding controls on any particular page. However, in ASP.NET MVC
application there is no toolbox available to drag and drop HTML controls on the
view. In ASP.NET MVC application, if you want to create a view it should contain
HTML code. So those developers who are new to MVC especially with web forms
background finds this a little hard.
To overcome this problem, ASP.NET MVC provides HtmlHelper class which
contains different methods that help you create HTML controls programmatically

HTML Helpers are categorized into three types:

1. Inline HTML Helpers


2. Built-in HTML Helpers
3. Custom HTML Helpers

There are different types of helper methods.


 Createinputs − Creates inputs for text boxes and buttons.
 Createlinks − Creates links that are based on information from the routing
tables.
 Createforms − Create form tags that can post back to our action, or to post
back to an action on a different controller.

The following is the list of Html Helper controls. 

 Html.Beginform
 Html.EndForm
 Html.Label
 Html.TextBox
 Html.TextArea
 Html.Password
 Html.DropDownList
 Html.CheckBox
 Html.RedioButton
 Html.ListBox
 Html.Hidden
Below are Strongly Type Html Helper methods, this will allow us to check compile
time errors. We get Model's Property intelligence at Runtime.

 Html.LabelFor
 Html.TextBoxFor
 Html.TextAreaFor
 Html.DropDownListFor
 Html.CheckBoxFor
 Html.RadioButtonFor
 Html.ListBoxFor
 Html.HiddenFor

Example of Using HTML HELPER

@using (Html.BeginForm("Index", "Home", FormMethod.Post))

<br />

@Html.Label("Enter Emp Name")

@Html.TextBox("EmpName")

<br />

@Html.Label("Enter Emp Designation")

@Html.TextBox("EmpDesig")

<br />
@Html.Label("Enter Employee Email Address")

@Html.TextBox("EmpEmail")

<br />

@Html.Label("Enter Name")

@Html.TextBox("txt1")

<br />

@Html.TextBox("txt2")

<br />

ColdDrink

@Html.CheckBox("Colddrink", false)

HTML Element

Example

TextBox

@Html.TextBox("Textbox1", "val") 
Output: <input id="Textbox1" name="Textbox1" type="text" value="val" />
TextArea

@Html.TextArea("Textarea1", "val", 5, 15, null) 


Output: <textarea cols="15" id="Textarea1" name="Textarea1"
rows="5">val</textarea>

Password

@Html.Password("Password1", "val") 
Output: <input id="Password1" name="Password1" type="password"
value="val" />

Hidden Field

@Html.Hidden("Hidden1", "val") 
Output: <input id="Hidden1" name="Hidden1" type="hidden" value="val" />

CheckBox

@Html.CheckBox("Checkbox1", false) 
Output: <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true"
/> <input name="myCheckbox" type="hidden" value="false" />

RadioButton

@Html.RadioButton("Radiobutton1", "val", true) 


Output: <input checked="checked" id="Radiobutton1" name="Radiobutton1"
type="radio" value="val" />

Drop-down list

@Html.DropDownList (“DropDownList1”, new SelectList(new [] {"Male",


"Female"}))
Output: <select id="DropDownList1" name="DropDownList1">
<option>M</option> <option>F</option> </select>
Multiple-select

Html.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket", "Chess"})) 


Output: <select id="ListBox1" multiple="multiple" name="ListBox1">
<option>Cricket</option> <option>Chess</option> </select>

6.Lamda Expression
static void Main(string[] args)
{
Console.WriteLine("lamda expression");
List<int> lst = new List<int>();
lst.Add(2);
lst.Add(3);
lst.Add(4);
lst.Add(5);
lst.Add(6);

foreach (int num in lst)


{
Console.WriteLine("Value "+num);
}
List<int> oddlist = lst.Where(x => x % 2 != 0).ToList();
Console.WriteLine("Odd number of the list");
foreach (int num in oddlist)
{
Console.WriteLine("Odd Value " + num);
}

Console.ReadKey();
}
List<int> lst = new List<int>();
lst.Add(2);
lst.Add(3);
lst.Add(4);
lst.Add(5);
lst.Add(6);

List<int> listodd = lst.Where(num => num % 2 != 0).ToList();

foreach (int n in listodd)


{
Console.WriteLine("Value " + n);

List<string> lst = new List<string> { "Ali", "Aman", "Rahil", "Deepak",


"Ajay" };
string x = "";
for (int i = 0; i < lst.Count; i++)
{
x = x+" "+lst.FindAll(str => str.StartsWith("A"));
Console.WriteLine("Name starts with A "+x);
}

7.LINQ [Language Integrated Query Language]


LINQ has its own Query Processing Engine. The information returned by a LINQ
query is a collection of in-memory object which may be enumerated.

The LINQ concept treats the data source as an Object, rather than a Database. So
we may say, its an object that is queried. LINQ may query any type of data source, 
1. Whenever we write the sql query it does not show any compile time error
but linq show the compile time error if you use wrong syntax

2. Just like sql query linq is also use to fetch the data from data base

3. It is included in the C# that is why it is called integrated query language

4. It was introduce in .NET 3.0

5. It is use to query the data from the various data sources like XML document,
data set , web services, Collection Generics, SQL Database.

8.FILE UPLOAD PROCEDURE FROM CLIENT TO SERVER

STEP 1.

View Part

<input type="file" name="fupic" class="form-control" /><br />

Controller part
HttpPostedFileBase FUPic = Request.Files["fupic"];

string File = FUPic.FileName; //Only name will be store in FileName

HttpPostedFileBase is a class provide the access to file which is uploaded by the


client

Note: Here “fupic” is the name in html file control

Step 2

Create a folder in Server

Step 3

String n = File.FileName;

if (n != null)

file.SaveAs(Server.MapPath("~/Content/Profiles/"+file.FileName));

9.Authentication and Authorization


1. Windows authentication
2. Form-based authentication
3. Passport authentication

Authentication It is the process in which developer ensure the identity of the


user on the basis of login information first user authenticate whether the
authorize user is accessing the web site or not

Authorization Every user has a different level of access permission like admin has
the different and user has different rights. So in authorization process it is ensure
whether a particular user granted to access any resource or not. It is kind of
permission to access the particular resource

A web.config file is xml based configuration file with the help of this file we can
change the behavior of asp.net and also use for security compliances

1. Windows authentication It is default authentication mode in asp.net in


which user provides the login information and submit the form then
information check if information is correct then user gets the form in which
user id, password and key is mentioned. It is more useful in intranet
environment because in the intranet we have a network domain and all user
have windows account based on the level permission grant to user for
accessing the resources in which request directly goes to IIS [Internet
information services] to provide the authentication process.
2. Form-based authentication In which session management techniques are
involved in which user provide the credential either credential are store in
database or in text file after proper authentication of user id and password
stored in the cookies for in that session so user activity will be trace on the
basis of information which is stored in cookies

3. Passport authentication it is the centralized service provided by Microsoft it


allow user to create a single registration and the same name and password
can be use in any area of website where passport authentication is
implemented like MSN and Hotmail if you have user id and password of MSN
you can access the Hotmail also due to passport authentication

10.Distributed applications

Distributed applications are those which don't just run on a single computer but
are divided up amongst several networked computers working together.

To do this the application needs to be split into components which communicate


with each other to achieve the overall purpose of the application. Each computer
in the network runs one (or more) of these components which perform different
tasks.
Examples of distributed applications include industrial control systems,
telecommunication systems and scientific applications which require significant
computing power.

However, WCF is concerned with a form of distributed computing known as


'service oriented' applications (SOA's) which provide services to other
applications. 

11.EXCEPTION HANDLING IN MVC


Exception handling is the process of responding to the occurrence of exceptional
conditions requiring special processing. Exception handling is important in any
application.
In ASP.NET MVC we have a larger list of ways to handle exception such as:

 Try-catch-finally
 Overriding OnException method
 Using the [HandleError] attribute on actions and controllers
 Setting a global exception handling filter
 Handling Application_Error event
 Extending HandleErrorAttribute

1. try-catch-finally

Change the Index as in the following.

1. public ActionResult Index()  
2. {  
3.     int a = 1;  
4.     int b = 0;  
5.     int c = 0;  
6.     try  
7.     {  
8.         c = a / b; //it would cause exception.  
9.     }  
10.     catch (Exception ex)  
11.     {  
12.         return View("Error");  
13.     }  
14.     finally  
15.     {   
16.     }  
17.     return View();  
18. }  

Here we are generating an exception at "c = a / b;" inside the try block. In the
catch we are retuning a different view "Error". If you run the application you will
get an Error page in the browser. In an actual project we can also use the catch
block to log the error information.

2. Overriding OnException method

For this, remove the try block from the preceding code. We need to overwrite
OnException as in the following:

1. public ActionResult Index()  
2. {  
3.     int a = 1;  
4.     int b = 0;  
5.     int c = 0;  
6.     c = a / b; //it would cause exception.             
7.     return View();  
8. }  
9.   
10. protected override void OnException(ExceptionContext filterContext)  
11. {  
12.     string action = filterContext.RouteData.Values["action"].ToString();   
13.     Exception e = filterContext.Exception;  
14.     filterContext.ExceptionHandled = true;  
15.     filterContext.Result = new ViewResult()  
16.     {  
17.         ViewName = "Error"  
18.     };  
19. }  

3.OnException is a void method that takes an argument as an object


of ExceptionContext that has all the information about the exception that can be
used to log. We need to set ExceptionHandled = true for the ExceptionContext
object. We can handle the exception generated from all the actions from a specific
controller. We can get the action name from ExceptionContext as in:

1. string action = filterContext.RouteData.Values["action"].ToString();   

There is the problem with this approach that we cannot reuse the exception
handling logic across multiple controllers. That is where global error handling is
useful.

4. Using HandleError Attribute

This is a simple way to handle exceptions in MVC. Remove the OnException


implementation from the previous code. Use the following procedure to do that.

Step 1
Add <customErrors mode="On" ></customErrors> in web.config under
<system.web>.
Step 2
Decorate the action with [HandleError] as:

1. [HandleError]  
2. public ActionResult Index()  
3. {  
4.    int a = 1;  
5.    int b = 0;  
6.    int c = 0;  
7.    c = a / b; //it would cause exception.   
8.    return View();  
9. }  

We can handle a different exception with a different view with [HandleError] as in


the following:

1. [HandleError]  
2. [HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error
1")]  
3. [HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View 
= "Error2")]  
4. public ActionResult Index()  
5.  {  
6.      int a = 1;  
7.      int b = 0;  
8.      int c = 0;  
9.      c = a / b; //it would cause exception.             
10.      return View();  
11.  }  

Here we should place a specific HandleError at the bottom. If we reverse the order
of the HandleError attribute then the Error.cshtml will always be displayed.
In the same way we can decorate our controller with HandleError. This would
handle the exception generated from all the actions from a specific controller.

5.Setting a global exception handling filter

For this we need to ensure that HandleErrorAttribute is added in


RegisterGlobalFilters of the FilterConfig file of App_start and registered in
Application_Start. No need to decorate our action and controller with
[HandleError].

6. Extending HandleErrorAttribute

We can also create our own Exception Handler by inheriting from


HandleErrorAttribute as in the following:

1. public class MyExceptionHandler : HandleErrorAttribute  
2. {  
3.      public override void OnException(ExceptionContext filterContext)  
4.      {  
5.           if (filterContext.ExceptionHandled ||
filterContext.HttpContext.IsCustomErrorEnabled)  
6.            {  
7.                return;  
8.            }  
9.            Exception e = filterContext.Exception;  
10.            filterContext.ExceptionHandled = true;  
11.            filterContext.Result = new ViewResult()  
12.            {  
13.                ViewName = "Error2"  
14.            };  
15.     }  
16. }

12.BOOTSTRAP
Bootstrap is a free and open-source CSS framework directed at
responsive, mobile-first front-end web development. It contains CSS- and
(optionally) JavaScript-based design templates
for typography, forms, buttons, navigation, and other interface components.
Bootstrap is a web framework that focuses on simplifying the development of
informative web pages (as opposed to web apps). The primary purpose of adding it
to a web project is to apply Bootstrap's choices of color, size, font and layout to
that project. As such, the primary factor is whether the developers in charge find
those choices to their liking. Once added to a project, Bootstrap provides basic
style definitions for all HTML elements. The result is a uniform appearance for
prose, tables and form elements across web browsers. In addition, developers can
take advantage of CSS classes defined in Bootstrap to further customize the
appearance of their contents. For example, Bootstrap has provisioned for light-
and dark-colored tables, page headings, more prominent pull quotes, and text
with a highlight.
Bootstrap also comes with several JavaScript components in the form
of jQuery plugins. They provide additional user interface elements such as dialog
boxes, tooltips, and carousels. Each Bootstrap component consists of an HTML
structure, CSS declarations, and in some cases accompanying JavaScript code. They
also extend the functionality of some existing interface elements, including for
example an auto-complete function for input fields.
The most prominent components of Bootstrap are its layout components, as they
affect an entire web page. The basic layout component is called "Container", as
every other element in the page is placed in it. Developers can choose between a
fixed-width container and a fluid-width container. While the latter always fills the
width of the web page, the former uses one of the four predefined fixed widths,
depending on the size of the screen showing the page:

 Smaller than 576 pixels


 576–768 pixels
 768–992 pixels
 992–1200 pixels
 Larger than 1200 pixels
Example:-
<div class="jumbotron text-center">
  <h1>My First Bootstrap Page</h1>
  <p>Resize this responsive page to see the effect!</p>
</div>

<div class="container">
  <div class="row">
    <div class="col-sm-4">
      <h3>Column 1</h3>
      <p>Lorem ipsum dolor..</p>
    </div>
    <div class="col-sm-4">
      <h3>Column 2</h3>
      <p>Lorem ipsum dolor..</p>
    </div>
    <div class="col-sm-4">
      <h3>Column 3</h3>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
</div>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy