SlideShare a Scribd company logo
ASP.NET MVC
Training – Part 1
AN ASP.NET MVC INTRODUCTION
Lee Englestone (@LeeEnglestone)
Tech Lead @ Kitbag.com
www.ManchesterDeveloper.com
Overview
 This primer covers Microsofts implementation of
the MVC pattern the ASP.NET MVC Framework
 Examples shown in C# but we use VB.NET and
there are some slight differences
 Part 1
 MVC Pattern, Models, Views, Controllers, Actions,
Routing, ActionFilters, Razor, Layout Views,
Capturng Input
 Part 2
 HtmlHelpers, PartialViews, Areas, Bundling,
Minification, Scaffolding, TDD/Unit Testing,
Dependency Injection, Bootstrap, Custom mobile
views, ModelAttributes, ModelState, AsyncController
MVC Pattern/Architecture
ViewController
Model
Initialises
Selects and
Renders
Bound to
Separation of Concerns
• Controller = Code
• View = UI
• Model = Data
ASP.NET MVC v WebForms
WebForms
 Maintain states with
VIewState, Postbacks and
Page Events
 One big form on each page
 Less control over rendered
HTML
MVC
 Does not automatically
maintain state between
requests. Uses HTTP GET and
POST
 Can have multiple forms on
a page
 More control over rendered
HTML
 TDD a lot easier
 Seperation of Concerns
Note : MVC does not replace WebForms. WebForms are not evil and they
can also be used with best practices. But it’s easier to see the benefits of
using MVC (In my opinion) especially in Greenfield development
Url Structure
 Uses Url Routing (not to be confused with re-writing)
 Completely configurable
 By default
 http://www.site.com/{Controller}/{Action}/{Id}
 For example /Product/View/Adidas-bag
 If using ‘Areas’ then..
 http://www.site.com/{Area}/{Controller}/{Action}/{Id}
Routing
 Routes kept in RouteTable
 Defined by default in
App_Start/RouteConfig.cs
 Routes urls in an
expected format to an
Action on Controller
 Can have restrictions..
 i.e. Id must be integer or
2 characters long
The default route (if none provided is Home/Index)
Exercise : Create a new
MVC Application
Exercise : Create a new
MVC Application
ASP.NET MVC
Solution Structure
 It should be obvious
where Models, Views and
Controllers live
 Content = .css files
Controllers
 The entry point of http / page
requests
 Mapped to by Routing
 Contain ‘Action’ methods
 For example returning views,
content, redirects
 Inherit from
System.Web.Mvc.Controller
class
 AsyncController also exists
(Discussed in Part 2)
Actions
 Methods on Controllers
 If no action is present in url, then the Index method is called (if exists)
so /home would execute Index Action on HomeController
These are just
returning empty
views at the moment
By default it will a
return a view with the
same name as the
Action
ViewBags are
dynamic objects..
ViewBags
 Are dynamic objects
 They circumvent strongly typing model properties
in views so use sparingly and only if necessary
 We don’t use ViewBags
 It’s a much better practice to instantiate a
‘Model’ with populated data and pass into the
view
ActionResult Types
 EmptyResult
 ContentResult*
 JsonResult*
 RedirectResult*
 RedirectToRouteResult
 ViewResult*
 PartialViewResult*
 FileResult
 FilePathResult
 FileContentResult
 FileStreamResult
 JavaScriptResult
*The main ones you’ll use
The Following things can be returned from Actions
Exercise : Run Application
 Hit F5
Note: This is /Home/Index
i.e Home Controller, Index
Action
This design is the
Bootstrap css framework
(Discussed in Part 2)
Models
 Models are usually simple classes with
a number or properties which will be
used in the Views
 Properties can be decorated with
different attributes to provide
additional functionality (Covered in
Part 2)
Views
 Views are returned from Controllers
 Before the View is returned a Model can be
bound to it
 They can access Properties on the Views Model in
in a type safe manner
Type of Model, the View uses
Binding to Properties on the Model
General code can be ran in
‘server’ blocks
Exercise : Create
HomeViewModel Model
 Create a new file/class in /Models called
HomeViewModel.cs
 Add a DateTime property on the class called Now
 Add a string property on the class called Message
Exercise : Bind HomeViewModel to
Index View
 In the Index Action on the HomeController..
 Instantiate a new HomeViewModel object
 Set Now property to DateTime.Now
 Give Message some text
 Return the Model in the View() result
Exercise : Update Home/Index
View to use HomeViewModel
 Open /Views/Home/Index.cshtml
 Add a @model declaration at the top to use your new
HomeViewModel
 Bind the Message property and the Now property to
somewhere on the page using the Razor syntax
 Press F5, refreshing page will hit controller and update time
each time
Razor View Syntax
 Razor is a markup syntax
 Uses @
 Used in .cshtml & .vbhtml files
 Slightly similar to WebForms <% %>
Code block & variable assignment
Using variable from earlier code
block
Iterating over collection
Conditional clauses
Layout Views
 Similar to WebForms .Master pages
 Provides common html for pages to share
 Provides area for page specific content
 Default located at ViewsShared_Layout.cshtml
Default Layout View
HtmlHelpers that create
Hyperlinks (Discussed in Part 2)
Where main body of Views will appear
Partial View (Discussed in Part 2)
Script Bundle (Discussed in Part 2)
Style Bundle (Discussed in Part 2)
Action Filters
 Can run code before / after an action is called
 Commonly used ‘out of the box’ ActionFilters
 [OutputCache(Duration=“60”)]
 Caches and returns the previous result of the Action
for the declared duration. Can VaryByParam etc
 [Authorize]
 Only allow action to be executed if current user is
authenticated
(HttpContext.Current.User.Identity.IsAuthenticated)
 [HttpPost]
 Only allow requests HttpPosts to this Action
Exercise : ActionFilters
 Add [OutputCache(Duration=60)] to Index
method on HomeController
 Run application
 Refresh browser and notice Action code is not
being executed subsequent times and the
previous Action result (View) is returned.
 Add [Authorize] to the About Action on the
HomeController
 Run application
 Try to go to About page and notice you’ll be
redirected to login page
Capturing Input with Forms
 Html Form “action” must be to a Controller Action
that expects an HttpPost. (Decorated with
[HttpPost])
 Name attributes of Inputs on the form need to
match property names on the Views Model
(HtmlHelpers do this automatically, discussed in
Part 2)
Capturing Input with Forms
These 2 are actually the same,
the latter uses HtmlHelpers
These are also the same
(kind of). First = better
Exercise : Capturing Form data
Extend the Model
 Add FirstName and LastName string properties to
HomeViewModel class
Extend the View to accept user input
 Update Home/Index View to include a form with FirstName and
LastName fields (see previous slide) whose action is Home/Save
Create Thanks Model
 Create new Model called Model/ThanksViewModel with
FirstName, LastName properties
Create Thanks View
 Create Home/Thanks View, that uses ThanksViewModel and
displays FirstName and LastName on page
Extend HomeController
 Add a Save Action that has [HttpPost] attribute, accepts
HomeViewModel and returns a ThanksViewModel to Thanks
View
Next time in Part 2..
 HtmlHelpers,
 PartialViews,
 Areas,
 Bundling,
 Minification,
 Scaffolding,
 TDD/Unit Testing,
 Dependency Injection,
 Bootstrap,
 Custom mobile views,
 ModelAttributes,
 ModelState,
 AsyncController
Ad

More Related Content

What's hot (20)

Mvc4
Mvc4Mvc4
Mvc4
Muhammad Younis
 
Developing an aspnet web application
Developing an aspnet web applicationDeveloping an aspnet web application
Developing an aspnet web application
Rahul Bansal
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.net
SHADAB ALI
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
eldorina
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
Divya Sharma
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
New Features of ASP.NET 4.0
New Features of ASP.NET 4.0New Features of ASP.NET 4.0
New Features of ASP.NET 4.0
Buu Nguyen
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
Barry Gervin
 
Asp net
Asp netAsp net
Asp net
Dr. C.V. Suresh Babu
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
Julie Iskander
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
Jennifer Estrada
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
LearnNowOnline
 
Advanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And ConstructsAdvanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And Constructs
Manny Siddiqui MCS, MBA, PMP
 
Industrial training seminar ppt on asp.net
Industrial training seminar ppt on asp.netIndustrial training seminar ppt on asp.net
Industrial training seminar ppt on asp.net
Pankaj Kushwaha
 
Active Server Page(ASP)
Active Server Page(ASP)Active Server Page(ASP)
Active Server Page(ASP)
Keshab Nath
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
ASP
ASPASP
ASP
Ramasubbu .P
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
baabtra.com - No. 1 supplier of quality freshers
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 

Similar to MVC Training Part 1 (20)

Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
ASP.MVC Training
ASP.MVC TrainingASP.MVC Training
ASP.MVC Training
Mahesh Sikakolli
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
rohitkumar1987in
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Sunpawet Somsin
 
MVC 4
MVC 4MVC 4
MVC 4
Vasilios Kuznos
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
Phuc Le Cong
 
Test
TestTest
Test
guest25229c
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
erdemergin
 
Build your website with angularjs and web apis
Build your website with angularjs and web apisBuild your website with angularjs and web apis
Build your website with angularjs and web apis
Chalermpon Areepong
 
MVC
MVCMVC
MVC
akshin
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
Eyal Vardi
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Sunpawet Somsin
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Build your website with angularjs and web apis
Build your website with angularjs and web apisBuild your website with angularjs and web apis
Build your website with angularjs and web apis
Chalermpon Areepong
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
Eyal Vardi
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Ad

More from Lee Englestone (11)

Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
Lee Englestone
 
Augmented Reality On iOS With ARKit Xamarin and C#
Augmented Reality On iOS With ARKit Xamarin and C#Augmented Reality On iOS With ARKit Xamarin and C#
Augmented Reality On iOS With ARKit Xamarin and C#
Lee Englestone
 
Reinventing Education Hackathon - LeARn
Reinventing Education Hackathon - LeARnReinventing Education Hackathon - LeARn
Reinventing Education Hackathon - LeARn
Lee Englestone
 
.NET Foundation website suggestions for improvement
.NET Foundation website suggestions for improvement.NET Foundation website suggestions for improvement
.NET Foundation website suggestions for improvement
Lee Englestone
 
25 Tips for Visual Studio
25 Tips for Visual Studio25 Tips for Visual Studio
25 Tips for Visual Studio
Lee Englestone
 
Tweet From Every Country Barcamp Manchester
Tweet From Every Country Barcamp ManchesterTweet From Every Country Barcamp Manchester
Tweet From Every Country Barcamp Manchester
Lee Englestone
 
Organisational Learning
Organisational LearningOrganisational Learning
Organisational Learning
Lee Englestone
 
Lincoln Hack 2018
Lincoln Hack 2018Lincoln Hack 2018
Lincoln Hack 2018
Lee Englestone
 
Familee bootstrapped-biz
Familee bootstrapped-bizFamilee bootstrapped-biz
Familee bootstrapped-biz
Lee Englestone
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
Lee Englestone
 
Visual Studio 2010 and ASP.Net 4
Visual Studio 2010 and ASP.Net 4Visual Studio 2010 and ASP.Net 4
Visual Studio 2010 and ASP.Net 4
Lee Englestone
 
Augmented Reality On iOS With ARKit Xamarin and C#
Augmented Reality On iOS With ARKit Xamarin and C#Augmented Reality On iOS With ARKit Xamarin and C#
Augmented Reality On iOS With ARKit Xamarin and C#
Lee Englestone
 
Reinventing Education Hackathon - LeARn
Reinventing Education Hackathon - LeARnReinventing Education Hackathon - LeARn
Reinventing Education Hackathon - LeARn
Lee Englestone
 
.NET Foundation website suggestions for improvement
.NET Foundation website suggestions for improvement.NET Foundation website suggestions for improvement
.NET Foundation website suggestions for improvement
Lee Englestone
 
25 Tips for Visual Studio
25 Tips for Visual Studio25 Tips for Visual Studio
25 Tips for Visual Studio
Lee Englestone
 
Tweet From Every Country Barcamp Manchester
Tweet From Every Country Barcamp ManchesterTweet From Every Country Barcamp Manchester
Tweet From Every Country Barcamp Manchester
Lee Englestone
 
Organisational Learning
Organisational LearningOrganisational Learning
Organisational Learning
Lee Englestone
 
Familee bootstrapped-biz
Familee bootstrapped-bizFamilee bootstrapped-biz
Familee bootstrapped-biz
Lee Englestone
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
Lee Englestone
 
Visual Studio 2010 and ASP.Net 4
Visual Studio 2010 and ASP.Net 4Visual Studio 2010 and ASP.Net 4
Visual Studio 2010 and ASP.Net 4
Lee Englestone
 
Ad

Recently uploaded (20)

Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 

MVC Training Part 1

  • 1. ASP.NET MVC Training – Part 1 AN ASP.NET MVC INTRODUCTION Lee Englestone (@LeeEnglestone) Tech Lead @ Kitbag.com www.ManchesterDeveloper.com
  • 2. Overview  This primer covers Microsofts implementation of the MVC pattern the ASP.NET MVC Framework  Examples shown in C# but we use VB.NET and there are some slight differences  Part 1  MVC Pattern, Models, Views, Controllers, Actions, Routing, ActionFilters, Razor, Layout Views, Capturng Input  Part 2  HtmlHelpers, PartialViews, Areas, Bundling, Minification, Scaffolding, TDD/Unit Testing, Dependency Injection, Bootstrap, Custom mobile views, ModelAttributes, ModelState, AsyncController
  • 3. MVC Pattern/Architecture ViewController Model Initialises Selects and Renders Bound to Separation of Concerns • Controller = Code • View = UI • Model = Data
  • 4. ASP.NET MVC v WebForms WebForms  Maintain states with VIewState, Postbacks and Page Events  One big form on each page  Less control over rendered HTML MVC  Does not automatically maintain state between requests. Uses HTTP GET and POST  Can have multiple forms on a page  More control over rendered HTML  TDD a lot easier  Seperation of Concerns Note : MVC does not replace WebForms. WebForms are not evil and they can also be used with best practices. But it’s easier to see the benefits of using MVC (In my opinion) especially in Greenfield development
  • 5. Url Structure  Uses Url Routing (not to be confused with re-writing)  Completely configurable  By default  http://www.site.com/{Controller}/{Action}/{Id}  For example /Product/View/Adidas-bag  If using ‘Areas’ then..  http://www.site.com/{Area}/{Controller}/{Action}/{Id}
  • 6. Routing  Routes kept in RouteTable  Defined by default in App_Start/RouteConfig.cs  Routes urls in an expected format to an Action on Controller  Can have restrictions..  i.e. Id must be integer or 2 characters long The default route (if none provided is Home/Index)
  • 7. Exercise : Create a new MVC Application
  • 8. Exercise : Create a new MVC Application
  • 9. ASP.NET MVC Solution Structure  It should be obvious where Models, Views and Controllers live  Content = .css files
  • 10. Controllers  The entry point of http / page requests  Mapped to by Routing  Contain ‘Action’ methods  For example returning views, content, redirects  Inherit from System.Web.Mvc.Controller class  AsyncController also exists (Discussed in Part 2)
  • 11. Actions  Methods on Controllers  If no action is present in url, then the Index method is called (if exists) so /home would execute Index Action on HomeController These are just returning empty views at the moment By default it will a return a view with the same name as the Action ViewBags are dynamic objects..
  • 12. ViewBags  Are dynamic objects  They circumvent strongly typing model properties in views so use sparingly and only if necessary  We don’t use ViewBags  It’s a much better practice to instantiate a ‘Model’ with populated data and pass into the view
  • 13. ActionResult Types  EmptyResult  ContentResult*  JsonResult*  RedirectResult*  RedirectToRouteResult  ViewResult*  PartialViewResult*  FileResult  FilePathResult  FileContentResult  FileStreamResult  JavaScriptResult *The main ones you’ll use The Following things can be returned from Actions
  • 14. Exercise : Run Application  Hit F5 Note: This is /Home/Index i.e Home Controller, Index Action This design is the Bootstrap css framework (Discussed in Part 2)
  • 15. Models  Models are usually simple classes with a number or properties which will be used in the Views  Properties can be decorated with different attributes to provide additional functionality (Covered in Part 2)
  • 16. Views  Views are returned from Controllers  Before the View is returned a Model can be bound to it  They can access Properties on the Views Model in in a type safe manner Type of Model, the View uses Binding to Properties on the Model General code can be ran in ‘server’ blocks
  • 17. Exercise : Create HomeViewModel Model  Create a new file/class in /Models called HomeViewModel.cs  Add a DateTime property on the class called Now  Add a string property on the class called Message
  • 18. Exercise : Bind HomeViewModel to Index View  In the Index Action on the HomeController..  Instantiate a new HomeViewModel object  Set Now property to DateTime.Now  Give Message some text  Return the Model in the View() result
  • 19. Exercise : Update Home/Index View to use HomeViewModel  Open /Views/Home/Index.cshtml  Add a @model declaration at the top to use your new HomeViewModel  Bind the Message property and the Now property to somewhere on the page using the Razor syntax  Press F5, refreshing page will hit controller and update time each time
  • 20. Razor View Syntax  Razor is a markup syntax  Uses @  Used in .cshtml & .vbhtml files  Slightly similar to WebForms <% %> Code block & variable assignment Using variable from earlier code block Iterating over collection Conditional clauses
  • 21. Layout Views  Similar to WebForms .Master pages  Provides common html for pages to share  Provides area for page specific content  Default located at ViewsShared_Layout.cshtml
  • 22. Default Layout View HtmlHelpers that create Hyperlinks (Discussed in Part 2) Where main body of Views will appear Partial View (Discussed in Part 2) Script Bundle (Discussed in Part 2) Style Bundle (Discussed in Part 2)
  • 23. Action Filters  Can run code before / after an action is called  Commonly used ‘out of the box’ ActionFilters  [OutputCache(Duration=“60”)]  Caches and returns the previous result of the Action for the declared duration. Can VaryByParam etc  [Authorize]  Only allow action to be executed if current user is authenticated (HttpContext.Current.User.Identity.IsAuthenticated)  [HttpPost]  Only allow requests HttpPosts to this Action
  • 24. Exercise : ActionFilters  Add [OutputCache(Duration=60)] to Index method on HomeController  Run application  Refresh browser and notice Action code is not being executed subsequent times and the previous Action result (View) is returned.  Add [Authorize] to the About Action on the HomeController  Run application  Try to go to About page and notice you’ll be redirected to login page
  • 25. Capturing Input with Forms  Html Form “action” must be to a Controller Action that expects an HttpPost. (Decorated with [HttpPost])  Name attributes of Inputs on the form need to match property names on the Views Model (HtmlHelpers do this automatically, discussed in Part 2)
  • 26. Capturing Input with Forms These 2 are actually the same, the latter uses HtmlHelpers These are also the same (kind of). First = better
  • 27. Exercise : Capturing Form data Extend the Model  Add FirstName and LastName string properties to HomeViewModel class Extend the View to accept user input  Update Home/Index View to include a form with FirstName and LastName fields (see previous slide) whose action is Home/Save Create Thanks Model  Create new Model called Model/ThanksViewModel with FirstName, LastName properties Create Thanks View  Create Home/Thanks View, that uses ThanksViewModel and displays FirstName and LastName on page Extend HomeController  Add a Save Action that has [HttpPost] attribute, accepts HomeViewModel and returns a ThanksViewModel to Thanks View
  • 28. Next time in Part 2..  HtmlHelpers,  PartialViews,  Areas,  Bundling,  Minification,  Scaffolding,  TDD/Unit Testing,  Dependency Injection,  Bootstrap,  Custom mobile views,  ModelAttributes,  ModelState,  AsyncController