The document provides an overview of ASP.NET MVC, including its architecture, advantages, folder structure, core components like controllers, views and action methods. It describes Model-View-Controller pattern, how controllers handle requests and return views with model data. It also compares ASP.NET MVC to Web Forms and lists some key selector attributes.
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Asp.net mvc
1. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
2. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Requirements
Requirements:
Knowledge of Object Oriented Programming(with c#)
HTML
CSS
Javascript/Jquery
3. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
4. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
MVC Architecture
MVC stands for Model, View and Controller
Separates application into three components - Model, View and Controller
Model:
data and business logic, model objects retrieve and store model state in a database
maintains the data of the application
View:
user interface
View display data using model and also enables them to modify the data
Controller:
Controller handles the user request
Renders the appropriate view with the model data as a response
6. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
MVC Architecture(contd…)
Request/Response in MVC Architecture
7. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
8. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Advantages of MVC-based web application
easier to manage complexity – dividing application into three components(model,
view & controller)
does not use view-state or server-based forms - makes the MVC framework ideal
for developers who want full control over the behavior of an application
provides better support for test-driven development (TDD)
works well for Web applications with large teams of developers and for Web
designers with full control over the application behavior
uses a front controller pattern that processes Web application requests through a
single controller. This enables you to design an application that supports a rich
routing infrastructure
9. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
10. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net Web Forms vs Asp.Net MVC
Asp.Net Web Forms:
follow a traditional event driven development model
has server controls
has state management (like as view state, session)
techniques
has file-based URLs i.e file name exist in the URLs must
have its physically existence
views are tightly coupled to code behind(ASPX.CS) i.e.
logic.
has Master Pages for consistent look and feels
has built-in data controls and best for rapid development
with powerful data access
has User Controls for code re-usability
not Open Source
Asp.Net MVC:
MVC is a lightweight and follow MVC (Model, View, Controller)
pattern based development model
has html helpers
no state management (like as view state, session) techniques
route-based URLs i.e URLs are divided into controllers and
actions & moreover based on controller not on physical file
Views and logic are kept separately
has Layouts for consistent look and feels
provide full control over markup and support many features that
allow fast & agile development
has Partial Views for code re-usability
Open Source
11. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
12. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
MVC Folder Structure
App_Data
Contain application data files like LocalDB, .mdf files, xml files and other data related files
App_Start
Contain class files which will be executed when the application starts
Typically, these would be config files like AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, RouteConfig.cs etc
Content
Contain files like CSS files, images and icons files
Controllers
Contains class files for the controllers
MVC requires the name of all controller files to end with "Controller“
e.g if you want to create “Home” controller then controller file will be “HomeController”
fonts
Fonts folder contains custom font files for your application
Models
Contain modal class files
Typically model class includes public properties, which will be used by application to hold and manipulate application data
13. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
MVC Folder Structure(contd…)
Scripts
Contains scripts like JavaScript, jQuery files for the application
Views
contains html files for the application
Typically, view file is a .cshtml or .vbhtml file depending on the language & engine you used in the application
Views folder includes separate folder for each controllers
Shared folder under View folder contains all the views which will be shared among different controllers
Additionally, MVC project includes following configuration files:
Global.asax
Global.asax allows you to write code that runs in response to application level events
Some events are: Application_BeginRequest, application_start, application_error, session_start, session_end etc
Packages.config
Packages.config file is managed by NuGet to keep track of what packages and versions you have installed in the
application
Web.config
Web.config file contains application level configurations
14. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
15. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Controller
Handles any incoming URL request
Controller is a class, derived from the base class
System.Web.Mvc.Controller
Contains public methods called Action methods
Controller and its action method handles incoming
browser requests, retrieves necessary model
data and returns appropriate responses
Every controller class name must end with a
word "Controller“
Also, every controller class must be located in
Controller folder of MVC folder structure
Add Controller Procedures:
1. In Solution Explorer, right click the Controller folder,
select Add, and then select Controller as shown
in figure:
16. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Controller(contd…)
Add Controller Procedures(contd…):
This opens Add Scaffold dialog as shown in figure:
Scaffolding is an automatic code generation
framework for ASP.NET web applications
Scaffolding reduces the time taken to develop
a controller, view etc.
Can develop a customized scaffolding template
using T4 templates
2. Add Scaffold dialog contains different templates
to create a new controller
For now, select "MVC 5 Controller - Empty" and click Add
It will open Add Controller dialog as shown below:
17. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Controller(contd…)
Add Controller Procedures(contd…):
3. In the Add Controller dialog, enter the name of
the controller
Remember, controller name must end with Controller
As for e.g, enter StudentController and click Add, as shown in figure:
This will create StudentController class with Index method in StudentController.cs file under Controllers folder as shown below:
namespace MVCApplication.Controllers
{
public class StudentController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
As you can see here, the StudentController class is derived from
Controller class
Every controller in MVC must derived from this abstract
Controller class
18. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Controller(contd…)
Now, as for example; return a string from Index action method of StudentController
namespace MVCApplication.Controllers
{
public class StudentController : Controller
{
// GET: Student
public string Index()
{
return "This is Index action method of StudentController";
}
}
}
If the above Index action method invoke from the browser, following output will be seen:
19. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
20. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
View
View is a user interface
View displays data from the model to the user
ASP.NET MVC views are stored in Views folder
Different action methods of a single controller class can render different views
Views folder contains a separate folder for each controller with the same name as controller
ASP.NET MVC supports following types of view files:
Add View Procedures
Integrate Controller, View and Model
View file extension Description
.cshtml C# Razor view. Supports C# with html tags.
.vbhtml Visual Basic Razor view. Supports Visual Basic with html tags.
.aspx ASP.Net web form
.ascx ASP.NET web control
=> Let us see an example
=> Let us see an example
21. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
22. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Methods
All the public methods of a Controller class are called Action methods
They are like any other normal methods with the following restrictions:
Must be public, cannot be private or protected
Cannot be overloaded
Cannot be a static method
23. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Methods(contd…)
MVC framework includes various result classes, which can be return from an action method
ActionResult
ActionResult is a base class of all the result type which returns from Action method
Result classes represent different types of responses such as html, file, string, json, JavaScript etc.
The ActionResult class is a base class of all the above result classes, so it can be return type of action
methods which returns any type of result listed above
24. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Methods(contd…)
Action method Parameters
Every action methods can have input parameters as normal methods
It can be primitive data type or complex type parameters
Example:
[HttpPost]
public ActionResult Edit(Student std)
{
// update student to the database
return RedirectToAction("Index"); //it will return the Index action method
}
[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with specified id
return RedirectToAction("Index"); //it will return the Index action method
}
25. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
26. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Selectors
Action selectors are the attributes that can be applied to an action method in a controller
It helps routing engine to select the correct action method to handle a particular request
MVC 5 includes the following action selector attributes:
ActionName
NonAction
ActionVerbs
ActionName Selector
Used when you want to invoke the action method with different name, than what is already given to the
action method
/Student/Index will invoke
public class StudentController : Controller
{
public ActionResult Index()
{
return View();
}
}
/Student/Home will invoke
public class StudentController : Controller
{
[ActionName(“Home")]
public ActionResult Index()
{
return View();
}
}
27. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Selectors(contd…)
NoAction Selector
NonAction selector attribute indicates that a public method of a Controller is not an action method
Use NonAction attribute when you want public method in a controller but do not want to treat it as an
action method
It cannot be invoked
/Student/Index will invoke
public class StudentController : Controller
{
public ActionResult Index()
{
return View();
}
}
When you try to invoke /Student/Index, returns HTTTP 404 status code
public class StudentController : Controller
{
[NonAction]
public ActionResult Index()
{
return View();
}
}
28. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Selectors(contd…)
ActionVerbs Selector
The ActionVerbs selector is used to control the selection of an action method based on a Http request method
For example, define two different action methods with the same name but one action method responds to an HTTP
Get request and another action method responds to an HTTP Post request
MVC framework supports different ActionVerbs, such as HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions &
HttpPatch
The following table lists the usage of http methods:
Http method Usage
GET To retrieve the information from the server. Parameters will be appended in the query string.
POST To create a new resource.
PUT To update an existing resource.
HEAD Identical to GET except that server do not return message body.
OPTIONS OPTIONS method represents a request for information about the communication options supported by
web server.
DELETE To delete an existing resource.
PATCH To full or partial update the resource.
29. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Action Selectors(contd…)
ActionVerbs Selector(contd…)
If you do not apply any attribute then it considers a GET request by default
The example of HttpGET and HttpPOST action verbs are shown below:
List<Student> student = new List<Student>();
//This action method passes the student data(according to id
passing to parameter) to the view
public ActionResult Edit(int id)
{
var std = student.Where(s => s.studentId == id).FirstOrDefault();
return View(std);
}
//This action method retrives all the student data from view
[HttpPost]
public ActionResult Edit(Student std)
{
//update database code here
return View();
}
Note that:
Can also apply multiple http verbs using
AcceptVerbs attribute
[AcceptVerbs(HttpVerbs.Post |
HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return View();
}
30. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
31. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Routing in MVC
ASP.NET introduced Routing to eliminate needs of mapping each URL with a physical file
Routing enable to define URL pattern that maps to the request handler, & this request handler can be a file
or class
Route
Route defines the URL pattern and handler
information
All the configured routes of an application stored in
RouteTable and will be used by Routing engine to
determine appropriate handler class or file for an
incoming request
32. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Routing in MVC(contd…)
ASP.NET introduced Routing to eliminate needs of mapping each URL with a physical file
Routing enable to define URL pattern that maps to the request handler, & this request handler can be a file
or class
Configure Route
Every MVC application must configure at least one route, which is configured by MVC framework by default
Routing configuration is in RouteConfig class, which is located under App_Start folder
Let us see inside RouteConfig class file & discuss
Multiple Routes
Can configure a custom route using MapRoute extension method
Need to provide at least two parameters in MapRoute, route name and url pattern
The Defaults parameter is optional
Can register multiple custom routes with different names
MVC framework evaluates each route in sequence Let us see inside RouteConfig class file & discuss
33. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Routing in MVC(contd…)
Route Constraints
Route constraints applies restrictions on the value of
parameters
constraints: new { id = @"d+" } - here, the value of
an id must be numeric
Register Routes
After configuring all the routes in RouteConfig class, you
need to register it in the Application_Start() event in the
Global.asax
The figure illustrate Route registration process:
34. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
35. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing
MVC 5 supports a new type of routing, called attribute routing
Attribute routing gives you more control over the URIs in your web application
Attribute Routing enables us to define routing on top of the controller action method
Enabling Attribute Routing
To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection
class during configuration
36. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing(contd…)
Enabling Attribute Routing(contd…)
In MVC5, we can combine attribute routing with convention-based routing
MapMvcAttributeRoutes() have to call before the Convention-based routing
Following are the code snipped
37. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing(contd…)
Attribute Routing Example
A route attribute is defined on top of an action method
Attribute Routing with Optional Parameter
can define an optional parameter in the
URL pattern by defining a question mark
(“?") to the route parameter
With Parameters
Use curly braces to define parametes, as shown below:
Parameters with default value
Use curly braces to define parametes, as shown
below:
38. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing(contd…)
Routing constraints
Routing constraints are used to make the
parameter of specific type
The general syntax for imposing certain
constraint is {parameter: constraint}
Implementing regex constraint
The given example only
supports the data of exactly 5
digits integer type
39. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing(contd…)
Route Prefix in Routing in ASP.NET MVC
set a common prefix for the entire controller (all
action methods within the controller)
Override Route Prefix
use a tilde (~) sign with the Route attribute to
override the route prefix
40. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing(contd…)
Default route
to define default route for any controller, define a Route attribute on top of the controller
41. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Attribute Routing(contd…)
Defining Route name
define a name of the route to allow easy URI
generation
Example:
public class StudentController : Controller
{
[Route("index",Name ="StudentHome")]
public ActionResult Index() {
return View();
}
}
We could generate a link using Url.RouteUrl:
<a href="@Url.RouteUrl(“StudentHome")">Product
Details</a>
Defining area in Asp.net MVC routing
Use RouteArea attribute to define area in asp.net
attribute routing
If we define the “RouteArea” attribute on top of the
controller, we can remove the AreaRegistration class
from global.asax
Example:
[RouteArea(“PostArea")]
[RoutePrefix("Category")]
public class StudentController : Controller
{
//URL: PostArea/Category/create
public ActionResult Create()
{
return View();
}
}
42. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
43. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle
Asp.net mvc page life cycle is totally different from webforms
there are no events like we have in web forms, e.g: pre-render, init, load etc.
whenever we request a url the only thing happens is some controller action is called and
response is rendered in the browser
There are seven main steps that happen when you make a request to an Asp.net MVC web
applications:
Routing
MvcHandler
Controller
Action Execution
View Result
View Engine
View
44. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
1. Routing
Asp.net Routing is the first step in MVC request cycle
Basically, it is a pattern matching system that matches the request’s URL against the registered URL
patterns in the Route Table
When matching pattern found in the Route Table, the Routing engine forwards the request to the
corresponding IRouteHandler for that request
The default one calls the MvcHandler
When matching pattern not found - routing engine returns a 404 HTTP status code against that
request
An application has only one RouteTable and this is setup in the Application_Start event of Global.asax
of the application
45. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
public class RouteConfig{
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
protected void Application_Start(){
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
public interface IRouteHandler{
IHttpHandler GetHttpHandler(RequestContext requestContext);
}
46. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
2. MvcHandler
It initiates the real processing inside ASP.NET MVC pipeline by using ProcessRequest method
protected internal virtual void ProcessRequest(HttpContextBase httpContext){
SecurityUtil.ProcessInApplicationTrust(delegate {
IController controller;
IControllerFactory factory;
this.ProcessRequestInit(httpContext, out controller, out factory);
try{
controller.Execute(this.RequestContext);
}
finally{
factory.ReleaseController(controller);
}
});
}
47. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
3. Controller
MvcHandler uses the IControllerFactory instance and tries to get a IController instance
If successful, the Execute method is called.
The IControllerFactory could be the default controller factory or a custom factory initialized
at the Application_Start event
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
}
48. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
4. Action Execution
Once the controller has been instantiated, Controller's ActionInvoker determines which specific action
to invoke on the controller
Action to be execute is chosen based on attributes ActionNameSelectorAttribute (by default method
which have the same name as the action is chosen) and ActionMethodSelectorAttribute(If more than
one method found, the correct one is chosen with the help of this attribute)
5. View Result
The action method receives user input, prepares the appropriate response data, and then executes
the result by returning a result type
The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult,
FileResult, and EmptyResult
49. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
6. View Engine
The first step in the execution of the View Result involves the selection of the appropriate View Engine
to render the View Result
It is handled by IViewEngine interface of the view engine
By default Asp.Net MVC uses WebForm and Razor view engines
You can also register your own custom view engine to your Asp.Net MVC application as shown below:
protected void Application_Start() {
ViewEngines.Engines.Clear(); //Remove All View Engine including Webform and Razor
ViewEngines.Engines.Add(new CustomViewEngine()); //Register Your Custom View Engine
}
50. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Asp.Net MVC request lifecycle(contd…)
7. View
Action method may returns a text string,a binary file or a Json formatted data
The most important Action Result is the ViewResult, which renders and returns an
HTML page to the browser by using the current view engine
51. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
52. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Razor Syntax
Razor view engine
Microsoft introduced the Razor view engine and packaged with MVC 3
Can write a mix of html tags and server side code in razor view
Razor uses @ character for server side code
Razor views files have .cshtml or vbhtml extension depending on language used
Razor Syntax
Razor syntax has following Characteristics:
Compact
Razor syntax is compact which enables you to minimize number of characters and keystrokes required to
write a code
Easy to learn
Razor syntax is easy to learn where familiar language like C# or Visual Basic can be used
Intellisense
Razor syntax supports statement completion within Visual Studio
53. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Razor Syntax(contd…)
How to write razor code:
Inline expression
Start with @ symbol to write server side C# or VB code with Html code
For example, write @Variable_Name to display a value of a server side variable
A single line expression does not require a semicolon at the end of the expression
Example: <h3>@DateTime.Now.ToShortDateString()</h3>
Multi-statement code block
Can write multiple line of server side code enclosed in braces @{ . . . }
Each line must ends with semicolon
Example:
@{
var date = DateTime.Now.ToShortDateString();
var message = "Hello World";
}
<h2>Today's date is: @date </h2>
<h3>@message</h3>
54. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Razor Syntax(contd…)
How to write razor code(contd…)
Display text from code block
Use @: or <text></text> to display texts within
code block
Example:
@{
var date = DateTime.Now.ToShortDateString();
var message = "Hello World";
@: Today's date is: @date
@message
}
@{
var date = DateTime.Now.ToShortDateString();
var message = "Hello World";
<text>Today's date is:</text> @date
@message
}
If-else condition
Write if-else condition starting with @ symbol
The if-else code block must be enclosed in
braces { }, even for single statement
Example:
@if(DateTime.IsLeapYear(DateTime.Now.Year))
{
@DateTime.Now.Year @:is a leap year
}
else {
@DateTime.Now.Year @:is not a leap year
}
55. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Razor Syntax(contd…)
How to write razor code(contd…)
for loop
Example:
@for(int i=0; I < 5; i++)
{
@i.ToString()
}
Declare variables
Declare a variable in a code block enclosed in brackets and
then use those variables inside html with @ symbol
@{
string str = ""; int i=1;
if(i > 0)
{
str = "Hello World!";
}
}
<p>@str</p>
Model
Use @model to use model object anywhere
in the view
Example:
@model Student
<h2>Student Detail:</h2>
<ul>
<li>Student Id: @Model.StudentId</li>
<li>Student Name: @Model.StudentName</li>
<li>Age: @Model.Age</li>
</ul>
56. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
57. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers
Will learn what are Html helpers and how to use them in the razor view
Html helper is a method that is used to render html content in a view
Html Helpers are implemented as extension method
Example:
HtmlHelper.ActionLink
@Html.ActionLink(“Create New”, ”Create”, ”Home”)
In the above example, @Html is an object of HtmlHelper class & ActionLink() is the
extension method
Html is a property of type HtmlHelper included in base class of razor view WebViewPage
HtmlHelper class generates html elements
For example, @Html.ActionList("Create New", "Create“, “Home”) would generate
anchor tag <a href="/Home/Create">Create New</a>
58. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
The following table lists HtmlHelper methods and html control:
HtmlHelper Strogly Typed HtmlHelpers Html Control
Html.ActionLink Anchor link
Html.TextBox Html.TextBoxFor Textbox
Html.TextArea Html.TextAreaFor TextArea
Html.CheckBox Html.CheckBoxFor Checkbox
Html.RadioButton Html.RadioButtonFor Radio button
Html.DropDownList Html.DropDownListFor Dropdown, combobox
Html.ListBox Html.ListBoxFor multi-select list box
Html.Hidden Html.HiddenFor Hidden field
Password Html.PasswordFor Password textbox
Html.Display Html.DisplayFor Html text
Html.Label Html.LabelFor Label
Html.Editor Html.EditorFor Generates Html controls based on data type of specified model property
e.g. textbox for string property, numeric field for int, double or other
numeric type.
59. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
Extension Method
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or
modifying the original type
An extension method is a special kind of static method, but they are called as if they were instance methods on the
extended type
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter
Example:
public class MyClass
{
public void Display()
{
Console.WriteLine("This is from display method");
}
}
public static class CustomExtensionClass
{
public static void NewMethod(this MyClass obj)
{
Console.WriteLine("This is from extension method");
}
}
static void Main(string[] args)
{
MyClass mycls = new MyClass();
mycls.Display();
mycls.NewMethod();
}
3
Out-
put
1
This is from display method
This is from extension method
2
60. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
Benefits Extension Method
Extension methods allow existing classes to be extended without relying on inheritance or having to change the
class's source code
If the class is sealed than there in no concept of extending its functionality. For this extension methods is
introduced
TextBox helper
To produce the HTML for a textbox with id=“firstname” and name=“firstname”
<input type=“text” name=“firstname” id=“firstname”/>
OR, we can use the “TextBox” htmlhelper : @Html.TextBox(“firstname”)
There are several other overloaded versions. To set a value along with the name : @Html.TextBox(“firstname”,
“Ram”)
To set HTML attributes, use the following overloaded version
@Html.TextBox(“firstname”, “Ram”, new{ style=“background-color:Red; color:White”,
placeholder=“Enter your name here” })
Some of the html attributes are reserved keywords. To use these attributes, use @ symbol as below :
@Html.TextBox(“firstname”, “Ram”, new{@class=“class_name”, @readonly=“true”})
61. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
Similarly,
To generate label for “First Name” : @Html.Label(“firstname”,”First Name”)
To generate Password field: @Html.Password(“password”)
To generate multi-line textbox(textarea) : @Html.TextArea(“comments”, “ ”, 5, 20, null)
To generate hidden field : @Html.Hidden(“id”)
Difference between TextBox & TextBoxFor
TextBoxFor is strongly typed html helper
Strongly typed html helpers are added in MVC2
Whether, use TextBox or TextBoxFor, the end result is the same, i.e they produce the same html
Example:
@model Student
@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })
62. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
Generating a dropdownlist control
The Html.DropDownList() method generates a select element with specified name, list items and
html attributes
A dropdownlist in MVC is a collection of SelectListItem objects
DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel)
Example:
@Html.DropDownList("Departments", new List<SelectListItem>
{
new SelectListItem { Text = "IT", Value = "1", Selected=true},
new SelectListItem { Text = "HR", Value = "2"},
new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department")
63. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
Generating a dropdownlist control(contd…)
To pass list of Departments from the controller, store them in "ViewBag"
public ActionResult Index()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = “Computer", Value = "0"});
items.Add(new SelectListItem { Text = “HR", Value = "1" });
items.Add(new SelectListItem { Text = “Payroll", Value = "2", Selected = true });
ViewBag.Departments = items;
return View();
}
Now in the "Index" view, access Departments list from "ViewBag"
@Html.DropDownList("Departments", "Select Department")
64. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
Generating a listbox control
The ListBox HTML helper renders the HTML <select> element with the multiple attribute, which allows the users to
make multiple selection
@Html.ListBox("Countries", new List<SelectListItem> {
new SelectListItem { Text = "Nepal", Value = "1", Selected = true }, new SelectListItem { Text = "China", Value = "2" },
new SelectListItem { Text = "US", Value = "3" }
}, "Select Country")
Generating a radiobuttonlist control
The Html.RadioButton() method creates an radio button element with a specified name, isChecked boolean and html
attributes
Male: @Html.RadioButton("Gender","Male")
Female: @Html.RadioButton("Gender","Female")
Generating a checkbox control
The Html.CheckBox() method generates a <input type="checkbox" > with the specified name, isChecked boolean and
html attributes
@Html.CheckBox("isNewlyEnrolled", true)
65. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Html Helpers(contd…)
HtmlHelper.Display
The Html.Display() generates a literal string for the specified property of model
@Html.Display("StudentName")
HtmlHelper.Editor
ASP.NET MVC also includes a method that generates html input elements based on the datatype
Editor() or EditorFor() extension method generates html elements based on the data type of the model
object's property
Property DataType Html Element
string <input type="text" >
int <input type="number" >
decimal, float <input type="text" >
boolean <input type="checkbox" >
Enum <input type="text" >
DateTime <input type="datetime" >
66. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
67. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Data transfer techniques
There are different techniques that can be used to transfer the data from Controller to View or passing data
between actions of a controller:
Model
ViewData
ViewBag
TempData
Sesions
68. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Data transfer techniques(contd…)
Model
The best and recommended way to pass the data from a Controller to View is by
using Model Classes
If we create a strongly typed view than that view is capable of accessing the
object/model that is being passed to it from the controller
There are three main type of Model classes
View model
o Data being worked in presentation layer
o Data in the view finds its place in one of the properties of the view model
classes
o Represents the data that the controller transmits after processing operations
for serving a response to the users
69. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Data transfer techniques(contd…)
Model (contd…)
Domain model
o Data being worked in middle(business logic) layer
o Referred to as the entity model or simply as the data model
o These entities are typically persisted by the data-access layer and consumed by services
that implement business process
Input model
o Collection of classes that describe the input data flow that goes from the web page
down to the controllers and backend
o Represent the data being uploaded with individual HTTP requests
o Model Binder in Asp.Net MVC maps data from HTTP requests to action method parameters
(i.e. properties if input model types)
70. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Data transfer techniques(contd…)
ViewBag & ViewData
Now, consider a scenario where we need to pass small amount of data from controller to view, then
for every such case if we start creating models then managing these models will become very
complex
For such requirements where we need to transfer small amount of data, we can use ViewData and
ViewBag
ViewBag
o ViewBag can be useful when you want to transfer temporary data (which is not included in
model) from the controller to the view
o It is a dynamic type property of ControllerBase class which is the base class of all controllers
o ViewBag only transfers data from controller to view, not visa-versa
o The ViewBag's life only lasts during the current http request, values will be null if redirection
occurs
71. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Data transfer techniques(contd…)
ViewBag & ViewData(contd…)
ViewData
o ViewData is similar to ViewBag
o ViewData is a dictionary which can contain key-value pairs where each key must be string
o ViewData only transfers data from controller to view, not visa-versa
o ViewData is derived from ViewDataDictionary which is a dictionary type
o ViewData value must be type cast before use
o ViewBag internally inserts data into ViewData dictionary. So the key of ViewData and property of ViewBag
must NOT match
o The ViewData’s life only lasts during the current http request, values will be cleared if redirection
occurs
72. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Data transfer techniques(contd…)
TempData
TempData is useful when you want to transfer data from one action method to another action method
of the same or a different controller
Can be used to store data between two consecutive requests. TempData values will be retained during
redirection
TempDataDictionary type
Internaly use Session to store the data
Value must be type cast before use, Check for null values to avoid runtime error
Call TempData.Keep() to keep all the values of TempData in a third request
Sessions
Session is the way to persist the data till the current session alive
If we need some data to be accessible from multiple controllers, actions and views then Session is the
way to store and retrieve the data
73. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
74. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Models
Represents domain specific data and business logic
Maintains the data of the application
Model objects retrieve and store model state in data storage like a database
Holds data in public properties
Usually, model classes reside in the Models folder in MVC folder structure. In fact
“Models” folder is optional and they can live anywhere
Models can even be present in a separate project
Model can be entities or business object
=> Let us see an example => (Next page)
75. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Models(contd…)
1
2
3
4
Let us see an another example, by creating
model in separate project
Let us see an example, as data access using
ADO.NET
Let’s see an example, as data access using
entity framework(both methodology:
using custom code or using wizard
76. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
77. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Binding
we use the Request.QueryString and Request
(Request.Form) object to get the value from HttpGet
and HttpPOST request. Accessing request values
using the Request object is a time wasting activity
Traditional ASP.NET style to get the http request
values in the action method
ASP.NET Model Binding
With model binding, MVC framework converts the
http request values (from query string or form
collection) to action method parameters
78. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Binding(contd…)
MVC framework automatically converts a query string to the action method parameters
Model binding works on both primitive type & complex type parameters
Binding to Primitive Type
The previous figure shows binding to primitive type parameters
Query string values will be converted into parameters based on matching name
can have multiple parameters in the action method with different data types
For example, “http://localhost/Student/Edit?id=1&name=Ram” would map to id and name
parameter of the following Edit action method:
public ActionResult Edit(int id, string name)
{
// your logic here
return View();
}
79. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Binding(contd…)
Binding to Complex Type
Model binding in MVC framework automatically converts form field data of HttpPOST request to the
properties of a complex type parameter of an action method
80. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Binding(contd…)
Inside Model Binding
Model binding is a two step process
First, it collects values from the incoming http request and second, populates primitive type or complex
type with these values
Value providers are responsible for collecting values from request and Model Binders are responsible for
populating values as shown in figure:
81. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Binding(contd…)
Working with data manipulation
Creating a view to insert data
FromCollection
Mapping posted data to controller action’s parameter types
UpdateModel & TryUpdateModel
Editing a model
Updating data
Unintended updates & preventing such unintended updates
Bind attribute
Insert, update, delete using entity framework
82. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
83. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Validation in MVC
Before an application stores data in a database, the application must validate the data
Data must be checked for potential security threats, verified that it is appropriately formatted by type and
size, and it must conform to our rules
DataAnnotations
ASP.NET MVC uses DataAnnotations attributes to implement validations
DataAnnotations includes built-in validation attributes for different validation rules, which can be applied
to the properties of model class
The DataAnnotations attributes found in System.ComponentModel.DataAnnotations namespace
Use ValidationSummary to display all the error messages in the view
Use ValidationMessageFor or ValidationMessage helper method to display field level error messages in
the view.
Check whether the model is valid before updating in the action method using ModelState.IsValid
Enable client side validation to display error messages without postback effect in the browser
84. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Model Validation in MVC(contd…)
DataAnnotations(contd…)
The following table lists DataAnnotations validation attributes:
Attribute Description
Required Indicates that the property is a required field
StringLength Defines a maximum length for string field
Range Defines a maximum and minimum value for a numeric field
RegularExpression Specifies that the field value must match with specified Regular Expression
CreditCard Specifies that the specified field is a credit card number
CustomValidation Specified custom validation method to validate the field
EmailAddress Validates with email address format
FileExtension Validates with file extension
MaxLength Specifies maximum length for a string field
MinLength Specifies minimum length for a string field
Phone Specifies that the field is a phone number using regular expression for phone numbers
85. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
86. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Layout View
The Layout view contains common parts of a UI, It is same like masterpage of ASP.NET webforms
Maintain a consistent look and feel across all the pages
_ViewStart.cshtml file can be used to specify path of layout page, which in turn will be applicable to all the
views of the folder and its subfolder
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can set the Layout property in the individual view also, to override default layout page setting of
_ViewStart.cshtml
Layout view uses two rendering methods:
Methods Description
RenderBody() Renders the portion of the child view(content page) that is not within a named
section. Layout view must include RenderBody() method.
RenderSection(string name) Renders a content of named section and specifies whether the section is required.
RenderSection() is optional in Layout view.
87. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Layout View(contd…)
The figure illustrates the use of RenderBody and
RenderSection methods:
RenderSection()
RenderSection() is a method of the WebPageBase
class
The first parameter to the "RenderSection()" helper
method specifies the name of the section
The second parameter is optional, and allows us to
define whether the section we are rendering is
required or not
If a section is "required", then Razor will throw an
error at runtime if that section is not implemented
within a view template that is based on the layout
file
RenderBody()
In layout pages, renders the portion of a content
page that is not within a named section
RenderBody is required, since it's what renders each
view
88. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
89. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Partial View
Partial view is a reusable view
A partial view is a view that is rendered within another view
If a partial view will be shared with multiple views of different controller folder then create it in the Shared
folder, otherwise you can create the partial view in the same folder where it is going to be used
Topics included under partial view:
Why should we use Partial View?
Comparasion with Views
Create Partial View //Example
Render Partial View
Why should we use Partial View?
Partial views are an effective way of breaking up large views into smaller components
Reduce duplication of view content and allow view elements to be reused
If you have a complex page made up of several logical pieces, it can be helpful to work with each piece as its own
partial view
Follow the DRY principle in your views
Note: (DRY Principle)
duplication in logic should be eliminated via abstraction
duplication in process should be eliminated via automation
References: http://deviq.com/don-t-repeat-yourself/
90. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Partial View(contd…)
Comparasion with Views
Partial views are created like any other view
There is no semantic difference between a partial view and a regular view – they are just rendred
differently
Same view can be used as both View and Partial View
The main difference between how a view and a partial view are rendered is that partial views do not run
_ViewStart.cshtml
Create Partial View
Render Partial View
render the partial view in the parent view using html helper methods: Partial() or RenderPartial() or
RenderAction()
Html.Partial()
o @Html.Partial() helper method renders the specified partial view
o It accept partial view name as a string parameter and returns MvcHtmlString
=> Let us see an example
91. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Partial View(contd…)
Render Partial View(contd…)
Html.Partial()
o @Html.Partial() method doesn't need to be in code block because it returns a html string
Html.RenderPartial()
o Same as the Partial method except that it returns void
o Writes the resulted html of the specified partial view into a http response stream directly
o Because it doesn’t return a result, it must be called within a Razor code block
Html.RenderAction()
o Invokes a specified controller and action & renders the result as a partial view
o The specified Action method should return PartialViewResult using the Partial() method
Let us see an example
<body>
@Html.Partial("_PartialViewName")
</body>=> Contd…
@{
Html.RenderPartial("_PartialViewName“)
}
92. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
93. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Areas
Areas introduced by ASP.NET MVC 2
Area allows us to partition large application into smaller units
where each unit contains separate MVC folder structure
Each area includes AreaRegistration class
AreaRegistration class overrides RegisterArea method to map the
routes for the area
Finally, all the area must be registered in Application_Start event
in Global.asax.cs as AreaRegistration.RegisterAllAreas()
=> Let us see an example
Areas Folder Structure
94. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Contents
Requirements
MVC Architecture
Advantages of MVC-based web application
Asp.Net Web Forms vs Asp.Net MVC
MVC Folder Structure
Controller
View
Action Methods
Action Selectors
Routing
Attribute Routing
Asp.Net MVC request lifecycle
Razor Syntax
Html Helpers
Data transfer techniques
Models
Model Binding
Model Validation in MVC
Layout View
Partial View
Areas
Bundling and Minification
95. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Bundling & Minification
Bundling
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
The following figure illustrates the bundling techniques:
Minification
Minification technique optimizes script or css file size by removing unnecessary white space and
comments and shortening variable names to one character
Without Bundling With Bundling
96. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Bundling & Minification(contd…)
Bundle Types
MVC framework provides ScriptBundle, StyleBundle and DynamicFolderBundle classes.
ScriptBundle does minification of JavaScript files
StyleBundle does minification of CSS files
ScriptBundle in ASP.NET MVC
We will learn how to create a bundle of multiple JavaScript files in one http request.
ASP.NET MVC includes ScriptBundle class that does JavaScript minification and bundling
The BundleConfig.cs file is created by MVC framework inside App_Start folder by default where we can
write all the bundling code in BundleConfig.RegisterBundles() method
=> Next Page: Procedures to create Bundle
97. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Bundling & Minification(contd…)
Procedures to create bundle
Let us assume, we have two JavaScript files inside scripts folder - bootstrap.js and
respond.js, & we are going to create bundle of these files:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
ScriptBundle scriptBundles = new ScriptBundle("~/bundles/bootstrap");
scriptBndl.Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"
);
bundles.Add(scriptBundles);
BundleTable.EnableOptimizations = true;
}
}
98. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Bundling & Minification(contd…)
Procedures to create bundle(contd…)
Steps:
1. First of all create an instance of ScriptBundle class by specifing the bundle name as a constructor
parameter
2. Use Include method to add path of one or more JS files into a bundle using ~ sign
3. Add the bundle into BundleCollection instance, which is specified as a parameter in RegisterBundles()
method
4. Finally, BundleTable.EnableOptimizations = true enables bundling and minification in debug mode. If you
set it to false then it will not do bundling and minification
You can also use IncludeDirectory method of bundle class to add all the files under particular directory as
shown below:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/scripts").IncludeDirectory("~/Scripts/","*.js",true));
}
99. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Bundling & Minification(contd…)
Registration
MVC framework invokes BundleConfig.RegisterBundle() method from the Application_Start event in Global.asax.cs
file, so that it can add all the bundles into BundleCollection at the starting of an application
protected void Application_Start() {
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Using Wildcards
It is not advisable to changes the code whenever you upgrade the version of script file, so with the use of wildcards,
we don't have to specify a version of a script file
Can use {version} wildcard to pickup a version based on available version
public static void RegisterBundles(BundleCollection bundles) {
bundles.Add(new ScriptBundle("~/bundles/jquery")
.Include( "~/Scripts/jquery-{version}.js"));
}
100. Prepared By: Er. Kamal Bhusal | Email: kamalbhusal2010@gmail.com
Bundling & Minification(contd…)
Using CDN
Can also use Content Delivery Network to load script files
public static void RegisterBundles(BundleCollection bundles)
{
var cdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";
bundles.Add(new ScriptBundle("~/bundles/jquery", cdnPath)
.Include( "~/Scripts/jquery-{version}.js"));
}
Include ScriptBundle in Razor View
Use Scripts.Render() method to include specified script bundle at runtime
<head>
@Scripts.Render("~/bundles/bootstrap")
</head>
Now, if you run your project then you will find two script files is combined, minified and loaded in a single
request. Please make sure that you have set debug = false in web.config <compilation debug="false"
targetFramework="4.5"/>