MVC Notes
MVC Notes
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
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
Benefits of Ajax
By not performing a full postback and sending all form data to the
server, network utilization is minimized and quicker operations occur.
Disadvantages:-
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>
-------------------------------------------------
There are two ways to start the jquery with your applicaton
1. Offline
Offiline means you can download Jquery file from the official site
WWW.JQuery.com.
-------------------------------------------------
Disadvantages
All the scripts either Jquery or JavaScript are browser dependent so user can stop
the script by browser
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.
Example:
<script>
$(document).ready(function() {
$("#accordion-1" ).accordion();
});
</script>
//
<div id=”accordion-1”>
<div id=div1>
<h3>Tab 2</h3>
</div>
<div id=div2>
<h3>Tab 2</h3>
</div>
<div id=div3>
<h3>Tab 3</h3>
</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:
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.
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
)
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.
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.
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
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
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
It is more secure than ASP.net technology that lets down the cross
scripting done by impostor.
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
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
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>
<title>Index</title>
</head>
<body>
<div>
<hr />
@{
<br />
</div>
</body>
</html>
Controller
//ViewBag.result = n;
int n = 5, i, f = 1;
f = f * i;
ViewBag.res = f;
int num = 124;
ViewData["value"] = num;
return View();
For HyperLinking
@{
if(IsPost)
int i,n;
n=int.Parse(ViewBag.num);
for(i=1;i<=10;i++)
<br />
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
__________________________________________________________
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.
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;
namespace scaff1.Models
[Key]
}
Step2
Step 3
2. Choose Template (MVC controller with read/write action and view using
Entity Frame work)
4. Data context Class (This class represent the data base in Entity frame work
EmpDB)
5. View (Razor)
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
UNIT – 3
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.
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
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>
<title>Index</title>
</head>
<body>
<div>
<hr />
<table>
<tr>
<td>Enter Student Name</td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
@{
if(IsPost==true)
a = double.Parse(Request["s1"]);
b = double.Parse(Request["s2"]);
c=double.Parse(Request["s3"]);
sum = a + b + c;
<br />
<br />
<h4>Result</h4>
<hr />
</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
return View();
}
[HttpPost]
a = double.Parse(s1);
b = double.Parse(s2);
c = double.Parse(s3);
sum = a + b + c;
ViewBag.name = txtname;
ViewBag.sum = sum;
ViewBag.average = avg;
return View();
}
REQUEST OBJECT WITH DIFFERENT PAGE
@{
Layout = null;
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<style>
body {
background-color:lavender;
a{
text-decoration:none;
</style>
</head>
<body>
<div>
<hr />
<table>
<tr>
<td>Enter Principal</td>
</tr>
<tr>
</tr>
<tr>
<td>Enter Time</td>
<tr>
</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;
<span>Result @sum</span>
}
</div>
</body>
</html>
@{
Layout = null;
<!DOCTYPE html>
<html>
<head>
<title>SecondView</title>
</head>
<body style="background-color:lightgreen">
<div>
@{
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
//
// GET: /Home/
return View();
return View();
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 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
View
<div>
@{
foreach(string n in ViewBag.res)
<li style="font-weight:bold;color:red;font-size:20px;">@n</li>
</ul>
<hr />
<ol>
@{
}
</ol>
<hr />
<ol>
@{
<li style="color:maroon;font-size:20px;font-weight:bold;">@n</li>
</div>
Controller
//
// GET: /Home/
public ActionResult Index()
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
View Model
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
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
routes.MapRoute(
name: "Route2",
url: "R1/",
defaults: new { controller = "Home", action = "index2", id =
UrlParameter.Optional }
);
routes.MapRoute(
name: "SR2",
url: "SR1/",
);
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",
);
routes.MapRoute(
name: "Route3",
url: "R3",
defaults: new { controller = "Home", action = "Index2", id =
UrlParameter.Optional }
);
UNIT – 4
1. JSON
Ajax Implementation Using JSON and Jquery
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.
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
$(document).ready(function () {
___________________________________________________________________
______________
for(i=0;i<=1;i++)
res += "______________________________</br>";
$("#div1").html(res);
jsonobj = [{ "name": "Raman", "Age": "24", "Marks": "90" }, { "name": "Ram",
"Age": "30", "Marks": "95" }];
$("#div1").html(res);
View Coading
if (msg == "success")
alert("saved records");
})
Controller Method
//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 () {
nam = $("#name").val();
marks = $("#marks").val();
$.getJSON("/Home/insertion", { n: nam, m: marks }, function (msg)
{
if (msg == "success") {
alert('Record Inserted');
else
});
string msg;
bool j = dm.insertupdatedelete(q);
if (j == true)
msg = "success";
else
msg="failure";
Search Record
$("#searchbtn").click(function () {
if (msg == "find") {
else {
});
});
Controller part coading for search
int id = int.Parse(searchid);
string msg;
DataTable dt = dm.readbulkdata(q);
if (dt.Rows.Count > 0)
msg = "find";
else
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:
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
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 .
-----------------------------------------------------
1)Features of EF :-
1) Configuration
-----------------------
2) Command
---------------
-------------------------------------
------------------------------------
1. for insertion
SaveChanges(Object of Table)
if(ViewBag.tbl!="")
@Html.Raw(ViewBag.tbl);
Deletion
public ActionResult Delete()
{
int id = int.Parse(Request.QueryString["empid"].ToString());
// db.TBL_EMP.Attach(del);
db.TBL_EMP.Remove(emp);
db.SaveChanges();
Response.Redirect("/Home/Index");
return View();
Index Coading
{
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());
return View(emp);
Veiw of Details
@{
Layout = null;
<!DOCTYPE html>
@using ENTITYFRAMEWORKDEMO.Models
@model TBL_EMP
<html>
<head>
<title>Details</title>
</head>
<body>
<div>
<table>
<tr>
<td>Employee Name</td>
<td>
</td>
<td>Emplyee City</td>
<td>
</td>
<td>Employee Age</td>
<td>
</td>
<td>Salary</td>
<td>
</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
//
// GET: /Home/
table += "</table>";
ViewBag.tab = table;
return View();
[HttpPost]
db.TBL_EMP.Add(emp);
db.SaveChanges();
Response.Write("<script>alert('Records saved into database ');</script>");
Response.Redirect("/Home/Index");
return View();
int id = int.Parse(Request.QueryString["empid"].ToString());
db.TBL_EMP.Attach(del);
db.TBL_EMP.Remove(del);
db.SaveChanges();
Response.Redirect("/Home/Index");
return View();
View code
@{
if(ViewBag.tab!="")
@Html.Raw(ViewBag.tab )
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.
[OutputCache(Duration=15)]
string dt = DateTime.Now.ToLongTimeString();
ViewBag.dtime = dt;
return View();
[Authorize]
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
[HttpPost]
[ValidateInput(false)]
ViewBag.result = txtname;
return View();
STEAL CODE
</form>
Step1
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken()]
ViewBag.result = txtname;
return View();
}
Step2
@Html.AntiForgeryToken();
</form>
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.
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
<br />
@Html.TextBox("EmpName")
<br />
@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
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
Drop-down list
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);
Console.ReadKey();
}
List<int> lst = new List<int>();
lst.Add(2);
lst.Add(3);
lst.Add(4);
lst.Add(5);
lst.Add(6);
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
5. It is use to query the data from the various data sources like XML document,
data set , web services, Collection Generics, SQL Database.
STEP 1.
View Part
Controller part
HttpPostedFileBase FUPic = Request.Files["fupic"];
Step 2
Step 3
String n = File.FileName;
if (n != null)
file.SaveAs(Server.MapPath("~/Content/Profiles/"+file.FileName));
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
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.
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
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.
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. }
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.
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. }
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.
6. Extending HandleErrorAttribute
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:
<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>