of 72
8/10/2019 Lap trinh MVC-Mvc Book
1/72
1Learn MVC step by step
LEARN MVC STEP BY STEP
BY
SUKESH MARLA AND SHIVPRASAD KOIRALA
Join our 2 days offline extensive Mumbai MVC training batch
on Saturday and Sunday
Call :- 022-66752917 / 9870148461
Begin with MVC 9
INTRODUCTION 9
TALK ABOUT VISUAL 9
WEB TECHNOLOGIES 9
VISUAL IN WEB 10
WHAT IS ASP.NET? 10
WHAT IS WEB FORMS? 10
ASP.NET4.0 13
WHAT IS MVC? 13
WHAT IS ASP.NETMVC? 14
WHY ASP.NETWEB FORMS AND WHY ASP.NETMVC? 15
CONCLUSION 15
Whats next? 15
Pre-requisite for MVC 15
Lab1:- Creating a simple hello world ASP.NET MVC Application 16
STEP 1:-CREATE PROJECT 16
STEP 2:-ADD CONTROLLER 16STEP 3:-ADD VIEW 17
STEP 4:-RUN THE APPLICATION 17
Lab2:- Passing data between controllers and views 17
STEP 1:-CREATE PROJECT AND SET VIEW DATA 18
8/10/2019 Lap trinh MVC-Mvc Book
2/72
2Learn MVC step by step
STEP 2:-DISPLAY VIEW DATA IN THE VIEW. 18
So whats in the next Lab? 18
Lab 3:- Creating a simple model using MVC 18
STEP 1:-CREATE A SIMPLE CLASS FILE 18
STEP 2:-DEFINE THE CONTROLLER WITH ACTION 19
STEP 3:-CREATE STRONGLY TYPED VIEW USING THE CLASS 19
STEP 4:-RUN YOUR APPLICATION 19
Lab 4:- Creating simple MVC data entry screen 20
STEP 1:-CREATING YOUR DATA ENTRY ASPXPAGE 20
STEP 2:-CREATING THE CONTROLLER 20STEP 3:-CREATE THE VIEW TO DISPLAY THE CUSTOMER OBJECT 20
STEP 4:-FINALLY RUN THE PROJECT 20
Lab 5:- using HTML helper to create views faster 20
STEP 1:-CREATE THE CUSTOMER CLASS 21
STEP 2:-CREATING THE INPUT HTMLFORM USING HELPER CLASSES 21
STEP 3:-CREATE A STRONG TYPED VIEW BY USING THE CUSTOMER CLASS 22
STEP 4:-CREATING THE CONTROLLER CLASS. 22
Lab 6:- Unit test MVC projects 22
STEP 1:-CREATE THE SIMPLE DISPLAY CUSTOMER SCREEN PROJECT 23
STEP 2:-ADD A SIMPLE UNIT TEST PROJECT 23
STEP 3:-ADD APPROPRIATE PROJECT REFERENCES 23
STEP 4:-WRITE THE UNIT TEST 24
STEP 5:-FINALLY RUN THE UNIT TEST 24
Lab 7:- Understanding MVC outbound URLs 24
INTRODUCTION 24
STEP 1:-CREATE VIEWS 25
STEP 2:-CREATE CONTROLLER FOR THE VIEWS 25
STEP 3:-PROVIDE ACTIONS IN THE LINK 25
STEP 4:-ENJOY YOUR NAVIGATION 25
8/10/2019 Lap trinh MVC-Mvc Book
3/72
3Learn MVC step by step
Lab 8:- Understanding MVC routing 26
INTRODUCTION 26
STEP 1:-OPEN THE GLOBAL.ASAX.CS FILE 26
STEP 2:-CUSTOMIZING THE URLS 27
STEP 3:-RUN THE APPLICATION 27
SO WHATS IN THE NEXT LAB 27
Lab 9:- Validating and setting default values to MVC URLS 27
STEP 1:-CREATE A SIMPLE CUSTOMER MODEL 27
STEP 2:-CREATE THE CONTROLLER CLASS 27
STEP 3:-APPLY VALIDATION USING REGEX ON THE MVCROUTES 28
STEP 4:-TEST IF IT WORKS 28
Lab 10:- Partial views 29
STEP 1:-CREATE A SIMPLE VIEW WITH CONTROLLER 29
STEP 2:-CREATE A SIMPLE PARTIAL VIEW 29
STEP 3:-PUT SOMETHING IN PARTIAL VIEW 29
STEP 4:-CALL THE PARTIAL VIEW IN THE MAIN 29
STEP 5:-RUN THE PROGRAM AND SEE THE ACTION. 30
Lab 11:- Validation using Data Annotation 30
STEP 1:-DECORATE MODEL WITH DATA ANNOTATION 30
STEP 2:-CHANGE THE ASPXCODE 30
STEP 3:-ENABLE CLIENT VALIDATION 31
STEP 4:-WRITE YOUR CONTROLLER LOGIC 31
STEP 5:-RUN YOUR APPLICATION TO SEE THE ACTION 31
SUMMARY OF OTHER DATA ANNOTATION ATTRIBUTES 31
Lab 12:- MVC 3:- Razor 32
STEP 1:-INSTALL MVC3AND CREATE A PROJECT USING THE SAME 32STEP 2:-SELECT RAZOR 32
STEP 3:-ADD A VIEW AND INVOKE THE SAME FROM CONTROLLER. 33
STEP 4:-PRACTICE RAZOR SYNTAXES 33
PRACTICE 1:-SINGLE LINE CODE 33
PRACTICE 2:-MULTIPLE LINES OF CODE 33
PRACTICE 3:-FOR EACH LOOP AND IFCONDITIONS 33
PRACTICE 4:-DO NOT WORRY ABOUT @ 34
8/10/2019 Lap trinh MVC-Mvc Book
4/72
4Learn MVC step by step
PRACTICE 5:-TO DISPLAY @ 34
PRACTICE 6:-HTMLDISPLAY WITH RAZOR 34
Lab 13:- MVC Security (Windows Authentication) 34
STEP 1:-ENABLE WINDOWS AUTHENTICATION 34
STEP 2:-JUST SOME DEFECTS 35
STEP 3:-APPLY AUTHORIZE TAGS ON YOUR CONTROLLERS /ACTIONS. 35
STEP 4:-CREATE SETUP 35
STEP 5:-CREATE IISAPPLICATION 36
STEP 6:-PUBLISH 36
STEP 7:-RUN THE CONTROLLER AND ACTION 36
Lab 14:- MVC Security (Forms Authentication) 36
STEP 1:-DEFINE THE LOGIN PAGE CONTROLLER 36
STEP 2:-CREATE THE INDEX VIEW 37
STEP 3:-VALIDATE CREDENTIALS 37
STEP 4:-AUTHORIZE ATTRIBUTE 38
STEP 5:-CHANGE WEB.CONFIGFILE 38
STEP 6:-SEE FORMS AUTHENTICATION IN ACTION 38
Lab 15:- JSON, MVC and JQuery 38
STEP 1:-CREATE A SIMPLE CUSTOMER MODEL 38
STEP 2:-EXPOSE CUSTOMER OBJECT AS JSON 39
STEP 3:-CONSUME THE JSONCONTROLLER IN JQUERY 39
STEP 4:-RUN THE APPLICATION AND SEE THE DATA 40
Lab 16:- Session management in MVC (ViewData, ViewBag, TempData and session variables) 40
STEP 1:-CREATE TWO CONTROLLERS DEFAULTCONTROLLER1AND DEFAULTCONTROLLER2. 41
STEP 2:-SET SESSION,TEMPDATA,VIEWDATA AND VIEWBAG 41
STEP 3:-READ SESSION,TEMPDATA ,VIEWDATA AND VIEWBAG VALUES 41
Lab 17:- Asynch controllers 42
STEP 1:-INHERIT FROM ASYNCCONTROLLER CLASS 43
STEP 2:-MARK METHODS WITH ASYNC APPENDED 43
STEP 3:-CREATE THE COMPLETED METHOD 43
STEP 4:-ENSURE TO CREATE SOMEHEAVYMETHOD.ASPXVIEW 44
8/10/2019 Lap trinh MVC-Mvc Book
5/72
5Learn MVC step by step
STEP 5:-RUN AND ENJOY 44
Lab 18:- MVC bundling and Minification 44
UNDERSTANDING MINIFICATION 45
STEP 1:-CREATE A MVCPROJECT WITH EMPTY TEMPLATE 45
STEP 2:-CREATE A CONTROLLER WHICH INVOKES A VIEW 45
STEP 3:-RUN AND SEE HOW MULTIPLE CALLS ARE MADE. 45
STEP 4:-REFERENCING SYSTEM.WEB.OPTIMIZATION 46
STEP 5:-THE BUNDLECONFIG FILE 46
STEP 6:-CALL THE BUNDLE CONFIG FILE FROM GLOBAL.ASAX.CS FILE 46
STEP 7:-RENDER THE BUNDLES IN THE VIEW 47
STEP 8:-WATCH YOUR BUNDLING AND MINIFICATION IN REAL 47
Lab 19:- MVC View Model 47
WHAT KIND OF LOGIC VIEW MODEL CLASS WILL CONTAIN? 48
STEP 1:-CREATE THE CUSTOMER MODEL 48
STEP 2:-CREATING THE VIEW MODEL 48
STEP 3:-CONSUME VIEW MODEL IN THE VIEW 49
SHOULD VMBE COMPOSED OR INHERITED. 50
ADVANTAGES OF VM 50
Lab 20:- MVC Exception Handling 51
INITIAL SETUP FOR OUR LAB 51
LOCAL LEVEL EXCEPTION HANDLING 52
GLOBAL LEVEL EXCEPTION HANDLING 52
DISPLAYING ERROR DETAIL IN ERROR VIEW 53
DIFFERENT VIEWS FOR DIFFERENT EXCEPTIONS 53
LIMITATIONS OF HANDLEERRORATTRIBUTE 53
EXTENDING HANDLEERRORATTRIBUTE 54
RESOURCE CANNOT BE FOUNDEXCEPTION 55
HOW GLOBAL LEVEL HANDLEERRORATTRIBUTE IS DIFFERENT FROM APPLICATION_ERROR? 55
Lab 21:- Areas in MVC 55
WHAT IS AREA AND WHY AREA? 55
HOW TO USE AREAS? 56
AREAS VS.FOLDERS? 56
Interview Preparation 58
8/10/2019 Lap trinh MVC-Mvc Book
6/72
6Learn MVC step by step
8/10/2019 Lap trinh MVC-Mvc Book
7/72
7Learn MVC step by step
About Sukesh Marla
After working for so many years as a developer, as a trainer I thought I should move ahead now.
As an author I wrote many online technical articles and won some awards for some of them.
This all started when I first met one of my greatest mentor ever Mr. Shivprasad Koirala. That meeting was about an open
source project on accounting.
I also started my CodeProject journey with Shiv sir writing my very first article about Mock Testing and after that I never looked
back.
From Basic C# Fundamentals to MVC, WCF, WPF, BI and Design patterns Shiv sir was there to guide me every time. He is purely
a down to earth person.
What I do?
I am Trainer.
I am Technical Leader.
I am News Paper publisher.
I am an author (CodeProject.com, CSharpCorner.com andwww.sukesh-Marla.com).
I record videos for questpond.
Now I write books ;) Most importantly I am learner
My Success
Complete success of this book and my professional career goes to several people.
First credit goes to my Mom and Dad without whom I would have done nothing. Their hard work and blessings took me
into this position.
My youngerbrother Suraj MarlaHe is not between us now. When he was around I never thought about hugging him
but now I want to but I cant. I cant do anything for him now but can try to keep his memories alive and can say only
one thing to him I miss yo.u
My sister Ujjwala KaduThanks for all your support Ujju, Thanks for taking care of me, Thanks for each and everything
you did it my life. I cant even imagine a life without you.
My lovely wife Dipal Shah (Dipal Marla) In our 5+ yrs. of relation unlike most other wives she never expected too manythings from me. In fact, she supported me to get my goal and sacrificed many things. Thanks dear.
About Shivprasad Koirala
I would like to first start by thanking the two old eyes who made this person without any expectations, my dad and mom.
I have been very selfish to steal time from my kids (Sanjana, Simran and Aditya) and my wife ( Vishna) to complete this book.
So a big thanks to stand by me to ensure that this book comes alive.
I am blessed to have Raju as my brother who always keeps my momentum moving on.
Special thanks to Mr. Sukesh Marla with whom I had long fruitful technical discussion which has flown in the book and made
the book stronger.
Thanks to Mr.Shaam, Mr. Ajay and Miss Amrita for all the effort they have put in. It was their tiresome three months of support
that we have finally made it.
http://www.sukesh-marla.com/http://www.sukesh-marla.com/http://www.sukesh-marla.com/http://www.sukesh-marla.com/8/10/2019 Lap trinh MVC-Mvc Book
8/72
8Learn MVC step by step
Features of this book
26 stunning labs with full details which starts r ight from simple hello world programs and then moves towards
complicated topics like view model and security.
50 great MVC interview questions quickly get ready for MVC interviews. Answers are crisp and to the point, great
collection for last minute revision.
Book also has a DVD accompanied which has step by step MVC videos which help you to visually see how the labs are
actually done.
Web world has come far away. Any server side technology today needs proper integration with JSON and JavaScript.
Dedicated labs on JSON, JQUERY integration with MVC showing every detail how to implement the same.
Performance is one of the key factors when it comes to MVC. A full step by step lab on bundling and Minification
which covers in detail steps of how we can increase MVC performance.
Session management in MVC is very different from ASP.NET Web forms. In MVC we have more fine tuning with
different session management techniques like tempdata , viewdata and viewbag. A full lab step by step explaininghow each one of these techniques varies.
One of the greatest strength of MVC is URL customization. We can customize MVC URL using MVC routing. Two great
labs which explains how MVC routing works and how to validations on the URL.
RAZOR is a new view engine created to simplify view creation. A full lab with details steps of how to create a RAZOR
view and different types of RAZOR syntaxes.
Security is one of the important aspects in any web application. Two detail labs which explains step by step how to do
forms and windows authentication / authorization in MVC.
Parallel execution is one the important features in web application for performance. MVC has introduced concept of
async controllers. A dedicated lab which explains how MVC async controllers can be implemented.
Two dedicated labs on MVC deployment and Exception handling takes the book to greater heights.
If you are thinking of learning MVC then you are at the right place. Itsa complete book for learning MVC practically as
well as for preparing for interviews.
How is this book organized?
MVC is one of the most wanted skills and also complicated. The best way to learn such complicated skill is by going step by step
and doing things practically. In this book we have taken every feature of MVC and executed it step by step in form of 21 great
labs.
Every lab first starts with theory and understand and then goes step by step explaining the feature. Every lab is explained with
source code and print screens so that you do not miss out any details while executing the labs.
In case you miss out details we have also accompanied videos in the DVD so that you can know every step when you are doing
the practical. So start with the first Lab, get your mouse and keyboard running and if you are not able to understand something
start playing the videos for better understanding.
8/10/2019 Lap trinh MVC-Mvc Book
9/72
9Learn MVC step by step
Begin with MVC
Introduction
In 2008 Microsoft came up with something called as ASP.NET MVC and I was quite amazed about thefact Why one more
ASP.NET technology required and many people still pondering same.
Many people say ASP.NET MVC replaced ASP.NET Web Forms.
But thats not true. Both have their own pros and cons.
Nobody can tell or teach us what to use and when, but we can discuss about some facts which
will help us to make choice between both of them. This article does the same.
If you already know the difference between MVC and Web Forms very well then this chapter will help you to revise your
concepts.
Talk about Visual
All the evolution started with one single but very powerful word called Visual.
With the help of technologies like Visual Basic, Visual C++ Microsoft broughtup Visual into application development world.
Whats special about this Visual world?
In Visual world when we want to develop the UI we wont write much code
rater,
We will take some
controls from toolbox and place it the form
Position them in
the screen using mouse
Finally generate a code block in the code behind part which will respond
to specific user events.(Event driven programming)
In simple words it enabled RAD (rapid application development) of Graphical User applications. Features such as Drag and Drop
and intellisense made developers to focus more on the business functionality of the application rather than on UI design.
But this technique was limited to desktops, when it comes to web the only option left with Microsoft was ASP.
Web Technologies
When we say web technologies, we have classic ASP, php, jsp,ASP.NET Web Forms, ASP.NET MVC and many more.
We also try to find answers for some questions like,
What is ASP.NET?
What is ASP.NET Web Forms?
What is MVC?
What is ASP.NET MVC?
8/10/2019 Lap trinh MVC-Mvc Book
10/72
10Learn MVC step by step
Classic ASP is one of the web technology introduced by Microsoft. Biggest pain point with the classic ASP was spaghetti code
and Maintainability.
Let assume a scenario where you have some text boxes and a button. On button click you validate the data with the server and
if validation succeeds data will be stored into database and in case it fails, error message will be shown to user in the form of
red colored label.
You know whats the biggest problem with this scenario is? You have to do lots of stuffs by your own.
1. First make the self-post back by setting forms action attributes value to same page.2. Text box values are going to be cleared on button click, so only choice left will be retrieving values from posted data.
3. In case validation fails you have to explicitly
a. Set all values back to the corresponding text boxes from posted data
b. Show error message.
(Using Ajax is an alternate method. Here I was trying to explain the manual work need to be done with classic ASP)
Visual in Web
In internet world there was no place for Event driven programming. It works on request/response pattern. End user will make a
request to server with the help of a client application called browser.
1. End user puts URL of the application in the address bar and press enter. It will make GET request to server.
2. Server will send back the response.
3.
Response can be anything. It can be an image, a simple text or may be complex HTML.
4. If response is HTML and if it contains some submit buttons, when user click it, it wil l make a new POST request to
server.
5. Server will send the response again.
This entire communication happens with the help of HTTP protocol.
One thing which we should know about HTTP protocol is, its stateless. Server will treat every request as the new request. Once
the response is sent back it will just forget about the request.
Finally Microsoft came up with something called ASP.NET Web Forms, considering rapid application development and easy
learning in priority.
What is ASP.NET?ASP.NET is a Microsofts Web application framework built on Common language runtime for building dynamic web sites using
one of the programming languages like C#, VB.NET etc.
It supports 2 models Web Forms and ASP.NET MVC.
What is Web Forms?
Microsoft first brought up ASP.NET Web Forms which solved lots of problems in classic ASP.It simply created higher level
abstraction over stateless web and simulated stateful model for Web developers.
It introduced two new concepts
Self-postback (send post requestto same page)
ViewState (maintain control values during postbacks) are
introduced.
And the most interesting part is its not required to write even a single
line of code.
With Web Forms Microsoft tried to bring the Visual Basic model into web.
8/10/2019 Lap trinh MVC-Mvc Book
11/72
11Learn MVC step by step
Lets talk about advantages and disadvantages of Web Forms.
Advantages:
Rich server controls.
o While working with pure HTML you might have noticed, Things are not always
same at all place.
A UI which looks great in IE might distract in Firefox or vice versa.
ASP.NET has a support for Rich Server Controls which detects the browser and
generates html (sometimes JavaScript too)based on browser capability.
o Server controls alsoincludes some controls like GridView and ListView whose
data binding capabilities reduces lots of efforts and codes being written.
Support for ViewStateStateless nature of HTTP normally clear values in the controls between multiple requests. But
in Web Forms statefulness is achieved by storing last known state of every control within the client page itself in the
form of hidden field called ViewState.
Event driven programming
With the help of
a) Code behind
b) Self postback
c) ViewState
Microsoft introduced event
driven programming in internet
world.
Developer will no more rely on
POST, GET methods for handlinguser interactions with server.
For example she/he will drag
control say button to page, just double click it to generate the code block for handling users click on server, write
down the logic inside it. Thats it. She/he is not concerned with what happens inside.
Rapid application development
I dont think any explanation is required for this. Rich server controls, Event driven model and ViewState increases
the development speed by great extent, Developer will be abstracted from lots of the background complexities .
Less learning effort.
Using strong server controls and ViewState developer can develop real world applications with minimal HTML and
JavaScript skills.
Disadvantages: Unit Testing
In Web Forms code behind ends up with lots of event
handlers, making automatic unit testing an impossible
task.
When we talk about employing TDD, unit testing code
behind (presentation logic) becomes very important.
8/10/2019 Lap trinh MVC-Mvc Book
12/72
12Learn MVC step by step
Project Architecture
There is no fixed predefined Project Architecture for creating web applications when it comes to Web Forms.
Developers have full flexibility for choosing their own architecture.
One may use basic three layered architecture dividing the system into UI, Business layer and Data access layer or may
go with an advanced one like Model-View-Presenter. Even one may choose only code behind and write everything
there which is not at all considered as good practice.
Performance
ViewState became solution for some problems in classic ASP but it also brought up one new trouble. ViewState is
stored in the page itself effecting page size which in turn effects performance.
Reusability
Look at these examples I.
II.Lets say wewant to build 2 User screens1. Taxable Employee screen 2.
Nontaxable employee screen
Now most of the code behind logic is going to be same for both screensOne solution will be, add some if conditions in code behind and create a single UI.
This will violate SRP (Single Responsibility principle).
SRP says there should be only one reason because of which a software entity should get changed.
In above example employee form will be changed whenever any of the taxable/nontaxable information changes.
Less Control over HTML
In Web Forms many times we are not sure about what html we will get at the end making integration with JavaScript
frameworks like jQuery a difficult task.
8/10/2019 Lap trinh MVC-Mvc Book
13/72
13Learn MVC step by step
SEO
URLs are pointing to fixed ASPX pages which might be
decorated with some query string. They are not user friendly and affect SEO.
Less support for parallel development
ASPX page are tightly coupled with code behind files. So its not possible for 2 different developers towork on one
section (one on aspx and one on code behind) at same time.
ASP.NET 4.0
In ASP.NET 4.0 some good features were introduced to overcome some of the above problems
VewState: Provide the way to disable or control the size of the ViewState.
URL routing: Using URL routing we can provide our own URL in lieu of the physical path of the page.
ID: Now we have better control over Id of elements and thus integration with JavaScript framework become easier.
Even after the evolution of the revolutionary features of ASP.NET,
1. It was still not able to solve the problems of unit testing
2. We got some control over ID of elements, but not complete control over HTML.
What is MVC?
MVC is an architectural pattern which is has been around for sometimes now. Many are using it including Java. Its not a new
concept which Microsoft brought up. Before we go and talk about ASP.NET MVC lets clear out some terminologies.
PatternsIn simple words Pattern is a solution to a problem in a context.
Architectural PatternsArchitectural Pattern is something which solves our problem at sub system level/module level. It deals with the problem related
to architecture of a project. It explains us,
What all components should be there is the system? (Like UI, BAL,etc.)
How every component interact with each other?
What will be the entry point?
MVCWhen we talk about application we will be having input logic, business logic and UI logic and MVC is an architectural pattern
which let us develop an application having loosely coupling between each of these elements.
The main intention behind MVC pattern is separation of concerns. It makes presentation
(UI) ignorant of business and user interaction logic.According to MVC system should be
divided as M (Model), V (View) and C (Controller).
Modelis considered as smart and handles the
Business rules, logic and data and will be independent of other parts of MVC (controller
and View).
Controllerreceives and dispatches the request in
short it handles the user interaction and input logic. It knows about both Model and
View.
Viewis considered as dumb and is an output representation of model data. It may be an
excel sheet, a web page showing list of records or just a simple text. View knows about
only Model.
8/10/2019 Lap trinh MVC-Mvc Book
14/72
14Learn MVC step by step
What is ASP.NET MVC?
ASP.NET MVC is a Microsofts second Web application framework designed with
separation of concerns and testability in mind. It is built on CLR and completely based
on MVC.
ASP.NET doesnt have support for ViewState and server controls, so we get feel of old
web here.
Lets talk about Advantages and disadvantages of ASP.NET MVC
Advantages:
Project architecture- One of the advantages of using ASP.NET MVC is it
enforces separation of concerns.
Performance-ASP.NET MVC dont have support for view state, so there will
not be any automatic state management which reduces the page size and so
gain in performance.
Test Driven development and Reusability-
In MVC, controller is an independent class, so
automatic testing is possible featuring Test Driven
Development
Full control over HTML-
ASP.NET MVC doesnt support server controls,
only option available is using html input controls,
so we will have assurance aboutthe html getting rendered at the end and about the id of every element. It makes
integration with third party JavaScript libraries (like jQuery) easy.
Support for parallel development-
In ASP.NET MVC layers are loosely coupled with each other, so one developer can work on Controller, at the same
time other on View and third developer on Model. This is called parallel development.
SEO, URL routing and REST-
Rich routing features lets treat every URL as a resource supporting RESTful interfaces.
Also user-friendly and readable URL improves SEO.
Extensibility-
ASP.NETMVC supports multiple view engines like aspx, razor and if required we can create our own. Existing ASP.NET Features-ASP.NET MVC framework is built on top of matured ASP.NET framework and thus provides
developer to use many good features such as forms authentication, windows authentication, caching, session and
profile state management etc.
Disadvantages:
More learning effort-
Absence of event driven programming model and ViewState makes ASP.NET MVC a very difficult framework for
developers with no or little experience in web application development.
How ASP.NET MVC works
1. User makes the request for some resource in server (by
putting some URL in the browser).
2. Request comes to controller first (routing engine is the
one who is responsible for deciding which request will
be handled by which controller. In this article we wont
talk in depth about this behavior).
3. Controller if required talk to model for data.
4. Model operates on database (or on some other data
sources) and return data to controller.
8/10/2019 Lap trinh MVC-Mvc Book
15/72
15Learn MVC step by step
5. Controller chooses the appropriate view (like say Customer view which will may contain some html tables, drop downs,
textboxes).
6. Controller passes the data (model data retrieved in step 4) to chosen view (in step 5), where data will be populated as per
convenience.
7. Controller sends back view to the user.
(This was for get request, same happens for post. Only instead of putting URL in the browser user will do some action on
already requested page and flow start with controller.)Why ASP.NET Web Forms and Why ASP.NET MVC?
Each can be the best choice for a particular solution depending on the requirements of the application and the background o f
the developers involved. What to choose & when has more to do with business prospective than which one is better than
other.
Two important factors you should consider while making the choice is
1. Rapid application development-
When we want to develop something rapidly ASP.NET Web Forms is the best choice.
2. Unit testingor HTML-When automatic unit testing is the most important factorMVC is best.When our organization
has a group of talented HTML developers who will make UI for applications independently and we have to integrate
that UI to our final dynamic application, MVC is best, because in MVC we will get complete control over HTML.
Other than these, what you can do is, write down all your project requirement and try to compare them with Pros and Cons of
both Web Forms and MVC and if possible try to ask yourself some questions and point MVC and Web Forms accordingly.
Example -
1. Does your team have good experience with Web Forms or Windows Forms?
If yes then developers are already used to with ViewState and event driven programming now and migration to MVC
will be a difficult task.1 point to Web Forms.
2. Does your team have experience on ASP or non-Microsoft technologies such as android, IOS, JSP, RORor PHP?
MVC is a general architecture and so many are using it. Android, IOS, etc. by default works on MVC platforms.
In some web application development environment like PHP, JSP same request/response pattern is followed. Having
experience in one or more such technology will add one extra point to ASP.NET MVC.
3. Is JavaScript going to be used extensively?
If Yes, MVC gets the point because you get complete control over HTML. 1 point to ASP.NET MVC.
4. Looking for good performance?
If yes, 1 point to ASP.NET MVC.
5. Planning to reuse the same input/user interaction logic across multiple UI?
If yes, 1 point to MVC.
Conclusion
I think you should have equipped with enough information to make a decision what is best for your project. The complete
decision depends on your team and project requirement.
Whats next?
I think by now you would have got clear idea about Web Forms and MVC. So whats next? Lets do a step by step demo on MVC
and lets learn MVC from scratch. We will cover total 21 Labs. With each lab we will reach to a different level in MVC. You can
also find some videos about same labs in the DVD. Hope you will enjoy this journey. Wish you all the best.
Pre-requisite for MVC
Before we start the day lets ensure that you have all the ingredients to create a MVC application.
Visual Studio 2010 or the free Visual Web Developer 2010 Express. These include ASP.NET MVC 2 template by default.
Visual Studio 2008 SP1 (any edition) or the free Visual Web Developer 2008 Express with SP1. These do not include
ASP.NET MVC 2 by default. You must also download and install ASP.NET MVC 2 fromhttp://www.asp.net/mvc/ .
http://www.asp.net/mvc/http://www.asp.net/mvc/8/10/2019 Lap trinh MVC-Mvc Book
16/72
16Learn MVC step by step
So once you have all your pre-requisite itstime to start with the first lab.
Lab1:- Creating a simple hello world ASP.NET MVC Application
In this lab we will create a simple hello world program using MVC template.
We will create a simple controller
Attach the controller to simple index.aspx page
View the display on the browser.
Step1:- Create project
Create a new project by selecting the MVC 2 empty web application
template as shown in the figure.
Once you click ok, you have a readymade structure with appropriate
folders where you can add controllers, models and views.
Step 2:- Add controller
So lets go and add a new controller as shown in the figure.
Once you add the new controller you should see some kind of code snippet as shown in the below snippet.
public class Default1Controller : Controller
{
// GET: /Default1/
public ActionResult Index()
{
return View();
}
}
8/10/2019 Lap trinh MVC-Mvc Book
17/72
17Learn MVC step by step
Step 3:- Add View
Now that we have the controller we need
to go and add the view. So click on the
Index function which is present in the
control and click on add viewmenu as
shown in the below figure.
Add viewpops up a modal box to enter view name which will be invoked when
this controller action is called as shown in the figure below. For now keep the view
name same as the controller name and also uncheck the master page check box.
Once you click on the ok button of the view, you should see a simple ASPX page with
the below HTML code snippet. In the below HTML code snippet I have added This
is my first MVC application.
Index
This is my first MVC application
Step 4:- Run the application
If you do a CNTRL + F5 you should see an error as shown in the below figure. This error is obvious because we have not invoked
the appropriate
controller / action.
If you append controller
and action name on theURL you should be able to
see the proper view.
Lab2:- Passing data between controllers and views
Now that we have created a simple MVC hello world, its time to see how we can pass data from controllers to views.
The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display
purpose.
As an ASP.NET developer your choice would be to use,
Session variables
View state
Or some other ASP.NET state management mechanism like application object, cache, etc.
The problem with these object is the scope. ASP.NET session objects have session scope and view state has page scope. For
MVC we would like to see scope limited to controller and the view. In other words we would like to maintain data when the hit
comes to controller and reaches the view and after that the scope of the data should expire.
8/10/2019 Lap trinh MVC-Mvc Book
18/72
18Learn MVC step by step
Thats where the new session management technique has been introduced in ASP.NET
MVC framework i.e. ViewData.
Step1:- Create project and set view data
So the first step is to create a project and a controller. In the controller set the viewdata variable as shown in the below code
snippet and kick of the view.
public class DisplayTimeController : Controller
{
// GET: /DisplayTime/
public ActionResult Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}
}
Step 2:- Display view data in the view.
The next thing is to display data in the view by using the percentage tag. One important point to note is the view does not have
a behind code. So to display the view we need to use the
8/10/2019 Lap trinh MVC-Mvc Book
19/72
19Learn MVC step by step
}
Step2:- Define the controller with action
The next step is to add the controller and create a simple action display customer as shown in the below code snippet. Import
the model namespace in the controller class. In the action we created the object of the customer class, flourished with some
data and passed the same to a view named as DisplayCustomer.
public class CustomerController : Controller
{..
.
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;
return View("DisplayCustomer",objCustomer);
}
}
Step3:- Create strongly typed view using the class
We need to now join the points of MVC by creating views. So
right click on the view folder and click add view. You should see adrop down as shown in the figure. Give a view name, check
create a strongly typed view and bind this view to the customer
class using the dropdown as shown in the figure.
The advantage of creating a strong typed view is you can now get the
properties of class in the view by typing the model and . as shownin the figure.
Below is the view code which displays the customer property value.
We also have if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.
The customer id is
The customer Code is
100) {%>
This is a priveleged customer
This is a normal customer
Step 4:- Run your application
Hitcontrol + F5 and pat yourself for one more lab success.
8/10/2019 Lap trinh MVC-Mvc Book
20/72
20Learn MVC step by step
Lab 4:- Creating simple MVC data entry screen
Every project small or big needs data entry screens. In this lab we will create a simple customer data entry screen as shown in
the figure using MVC template.
Step1:- Creating your data entry ASPX page
The first step is to create the data entry page using the simple HTML form action tag as shown in the below code snippet. One
thing which we should notice is, action is pointing to the controller action i.e. DisplayCustomer.
Enter customer id :-
Enter customer code :-
Enter customer Amount :-
Step2:- Creating the controller
Below is the code snippet of displaycustomer which flourishes the customer object by collecting data from request.form and
sends the object to the view displaycustomer.
public class CustomerController : Controller
{
.
[HttpPost]
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
objCustomer.CustomerCode = Request.Form["Id"].ToString();
objCustomer.Amount =Convert.ToDouble(Request.Form["Amount"].ToString()); ;
return View("DisplayCustomer", objCustomer);
}
}
Step3:- Create the view to display the customer object
(Same as Lab 3)
Step 4:- Finally run the project
Final step is to run the project and see the output.
(You should be also able to test above 100 and
below 100 scenarios)
Lab 5:- using HTML helper to create views faster
Now there are two big issues with above lab:-
The complete HTML code was written manually. In other words, less productive. Its like going back to dark ages
where developers used to write HTML tags in notepad.
8/10/2019 Lap trinh MVC-Mvc Book
21/72
21Learn MVC step by step
Enter customer id :-
Enter customer code :-
Enter customer Amount :-
Lots of manual code was written in the controller to flourish the object and send data to the MVC view.
public class CustomerController : Controller
{
[HttpPost]
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
objCustomer.CustomerCode = Request.Form["Id"].ToString();
objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;
return View("DisplayCustomer", objCustomer);
}
}
In this lab we will see how to use MVC HTML helper classes to minimize the above manual code and increase productivity.
Step 1:- Create the Customer classCreate a simple customer class, please refer Lab 5 for the same.
Step2:- Creating the input HTML form using helper classes
HTML helper classes have readymade functions by which you can create HTML
controls with ease. Go to any MVC view and see the intellisense for HTML helper class
you should see something as shown in the figure.
By using HTML helper class you can create any HTML control like textbox, labels, list
box etc. just by invoking the appropriate function.
In order to create the form tag for HTML we need to use Html.BeginForm.
-- HTML input fields will go here
The above code will generate the below HTML
..
..
The HTML helpers beginform takes three input parameters action name (Method inside the controller), controller name
(actual controller name) and HTTP posting methodology (Post or GET).
If you want to create a text box, simply use the TextBox function of html helper class as shown in the below code. In this way
you can create any HTML controls using the HTML helper class functions.
Enter customer id :- x.Id)%>
The above code snippet will generate the below HTML code.
Enter customer id :-
8/10/2019 Lap trinh MVC-Mvc Book
22/72
22Learn MVC step by step
To create a data entry screen like the one shown in figure we need to the use the below code snippet.
Enter customer id :- x.Id)%>
Enter customer code :- x.CustomerCode) %>
Enter customer Amount :- x.Amount) %>
Step 3:- Create a strong typed view by using the customer class
So once you have created the view using the HTML helper classes its time to attach the customer class with view, please refer
lab 5 for the same.
Step4:- Creating the controller class.
The final thing is the controller code. The controller code now becomes very simple. The customer objectwill be auto flourished
as we have used the HTML helper classes. You will create the controller class as we did in Lab 4 but we do not need to write any
kind of code for connecting the HTML sc reens with controller, its all hidden and automated.
[HttpPost]
public ActionResult DisplayCustomer(Customer obj)
{
return View(obj);
}
Enjoy your output for different condition
of customer amount entered.
Mode HTML Element Helpers foryour reference:
Html.TextBoxFor()
Html.TextAreaFor()
Html.DropDownListFor()
Html.CheckboxFor()
Html.RadioButtonFor()
Html.ListBoxFor()
Html.PasswordFor()
Html.HiddenFor()
Html.LabelFor()
Html.BeginForm
Lab 6:- Unit test MVC projects
Just a quick recap, if we need to unit test the method BtnSave_click(written in the ASP.NET code behind), we have the
following problems:-
How do we create the sender and EventArgs object?
The code runs under HttpContext object, how do I mimicthem?
What about ASP.NET UI controls, how do I access them?
What about other ASP.NET object like session object,
application, how do I access them?
Note- Many developers would talk about mock test, rhino mocks etc. but still its cryptic and the complication increases with
session variables, view data objects, ASP.NET UI controls creating further confusion.
8/10/2019 Lap trinh MVC-Mvc Book
23/72
23Learn MVC step by step
So what we will do in this section is we will create a simple MVC application and we will do unit using VSTS unit test framework.
Step1:- Create the simple display customer screen project
The first step is to create a simple MVC project. We will use the same project which we have discussed in Chapter 2.
The controller class at the end of the day is a simple .NET class. For instance if you watch your project code closely, you can
easily see the customer controller class as shown below.
public class CustomerController : Controller
{
....
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;
return View("DisplayCustomer",objCustomer);
}
}
In simple words because this is a simple .NET class we can easily instantiate the class and create automated unit tests for the
same. Thats what exactly we are going to do in our next steps.
Step 2:- Add a simple unit test project
Lets use our VSTS unit test framework to test the controller class.
Note:In case you are a complete fresher to VSTS unit testing we would request to see the basic unit testing video from the DVD
where we have discussed how to unit test the simple .net class library.
Step 3:- Add appropriate project references
We need to add reference to the MVC application in our unit test project so that we can get hold of the controller class.
Once you add the references you should see the
MVC application in your project references as
8/10/2019 Lap trinh MVC-Mvc Book
24/72
24Learn MVC step by step
shown in the below figure.
Step 4:- Write the unit test
Once you have added the references open the unit test class i.e. UnitTest1.cs. In this class, create a simple test method calledas DisplayCustomer which is attributed by TestMethod attribute as shown in the code snippet.
Inside Test Method we are creating object of the controller clas s, invoking the controller action i.e. DisplayCustomer and then
checking if the view name is DisplayCustomer. If they are equal that means the test passes or else it fails.
[TestMethod]
public void DisplayCustomer()
{
CustomerController obj = new CustomerController();
var varresult = obj.DisplayCustomer();
Assert.AreEqual("DisplayCustomer", varresult.ViewName);
}
Step 5:- Finally run the unit test
Its time to run the test case by clicking on menuTest>>windows and then clicking test view.
On the test view right click on the test and run the selected
test case as shown in the figure.
If everything goes well you
should see green color indicating that the test has passed or else
you should see a red color with details regarding why the test failed.
Lab 7:- Understanding MVC outbound URLs
Introduction
When we talk about web applications end users would like to navigate from one page to other page. So as a simple developer
your first thought would be to just give page
names as shown in the figure.
So for example if you want to go and browse from
home.aspx to about.aspx give the anchor hyper
link page name and things should be fine.
By doing that you are violating MVC principles.
MVC principle says that hit should first come to
the controller but by specifying the first hit comes to the
8/10/2019 Lap trinh MVC-Mvc Book
25/72
25Learn MVC step by step
view. This bypasses your controller logic completely and your MVC architecture falls flat.
Ideally the actions should direct which page should be invoked. So the hyperlink should have actions in the anchor tags and not
the page names (view name).
Step 1:- Create views
Letscreate three views as shown in the below figure Home, About and Product.
Step 2:- Create controller for the views
Next step is to define controller actions which will invoke these views. In the below code snippet we have defined 3 actions
GotoHome (for home view), AboutUs (for about view) and SeeProduct (for product view).
public class SiteController : Controller
{
public ActionResult GotoHome(){return View("Home");}
public ActionResult AboutUs(){return View("About");}
public ActionResult SeeProduct(){return View("Product");}
}
Step 3:- Provide actions in the link
To invoke the actions rather than the views we need to specify the actions in the anchor tag as shown in the below codesnippet.
This is products
Go Home
About us
If you want to create the anchor l inks using the HTML helper classes you can use the action link function as shown in the below
code snippet.
The above code was for the products page, you can do the same type of navigations for the about us and the home page.
This is About us
Go Home
See Product
This is home page
See Product
About us
Step 4:- Enjoy your navigation
Execute the application and enjoy your navigationbetween home, about and product page.
8/10/2019 Lap trinh MVC-Mvc Book
26/72
26Learn MVC step by step
Lab 8:- Understanding MVC routing
Introduction
MVC Routing helps us to provide simplified and custom URL. MVC URL naming
convention by default depends on Controller class names and action names. If you see
the previous labs of MVC the way we were invoking MVC pages was by typing
ControllerName/ActionName.
So for example if we have a controller class with name clsProductDetails and action as
getProduct , your URL ends up with a format
http://localhost/clsProductDetails/getProduct . Now how user friendly is that URL for
simple end users? - It is absolutely not.
MVC routing maps your browser URL request to the controllers and actions. So when
any request is sent to a MVC site it first hits the routing collection
and then dependingon the values of URL appropriate
controller and action is invoked. By default MVC has a route
collection defined which maps the URL to default controller and
action name.
Lets go step by step exploring first the default routes provided and in the later steps we will customize the URL structure withuser friendly URL names.
Step 1:- Open the Global.asax.cs file
To see default mapping code, lets take the same customer project we had discussed in the
previous section and open the global.asax.cs.
You will see the below code which specifies default mappings:-
routes.MapRoute(
"Default", // Parameter 1
"{controller}/{action}/{id}", // Parameter - 2
new { controller = "Home", action = "Index", id = UrlParameter.Optional
}// - Parameter - 3
);
Let us try to understand the above default code:-
routes.MapRoute :-routes is a global collection in which
all routes are stored. This collection belongs to the
namespace System.Web.Routing. To add a route to the
routes collection we need to use the maproute function. maproute function needs three parameters to add a route to the
collection route name ( name) , structure of the URL ( url) and controller / action mapping.
Parameter 1, Route key name: -The first value in the maproute function is the key name (name). This value identifies the
map in the collection using this keyname. This name should be unique throughout the collection.
Parameter 2, Route structure: -The second value in the maprouteis the route structure. By default the value is "{controller}/
{action}/ {id}". This indicates that the user needs to send URL exactly like controller class name and action method name. The
last Id indicates that it can have input values as well.
Parameter 3, Controller and actions: -The third value specifies the controller class name and the action name which will
invoked depending on the URL structure provided. To provide controller and action names we need to specify new controller
= "Home", action = "Index", id = UrlParameter.Optional}. In this syntax the controller specifies the controller name, action
specifies the action name and id specifies whether this parameter is compulsory or optional.
http://localhost/clsProductDetails/getProducthttp://localhost/clsProductDetails/getProduct8/10/2019 Lap trinh MVC-Mvc Book
27/72
27Learn MVC step by step
Step 2:- Customizing the URLs
In our current project we are calling the Customer controller and the DisplayCustomer action using
http://localhost/Customer/DisplayCustomer.Lets say we want to customize this URL structure to more friendly structure like
http://localhost/View/ViewCustomer/.To achieve the same we need to change the parameter 2 in the above format.
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // -- parameter 2new { controller = "Customer", action = "DisplayCustomer", id =
UrlParameter.Optional }); // Parameter defaults
Below is the action function DisplayCustomer which will be invoked.
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer(){Id = 12,CustomerCode = "1001,Amount = 90.34};
return View("DisplayCustomer",objCustomer);
}
Step 3:- Run the application
If you run the application with above defined URL structure you should see
the below display.
So whats in the next Lab
In the next lab we will discuss how to validate MVC URL. All actions to MVC come via MVC URL and even data is fed via MVC
URL. So in the next section we will see how we can validate the data passed in the MVC URL.
Lab 9:- Validating and setting default values to MVC URLS
In the previous lab we have seen how to simplify the URL structure. But with simplified URL structure we would also like to put
validations. For example for this URLhttp://localhost/Customer/ViewCustomer/1001 we would like to ensure that
customercode 1001 as numeric .In other words anyone entering a MVC URL like
http://localhost/Customer/ViewCustomer/Shiv is invalid.
MVC framework provides a validation mechanism by which we can check on the URL itself if the data is appropriate. In this lab
we will see how to validate data which is entered on the MVC URL.
Step 1:- Create a simple customer model
The first is to create a simple customer class model which will be invoked by the controller.
public class Customer
{
public int Id { set; get; }
public string CustomerCode { set; get; }
public double Amount { set; get; }
}
Step 2:- Create the controller class
The next step is to create a simple controller class which has a collection of customer model object which was created in step 1.
public class CustomerController : Controller
{
List Customers = new List();
public CustomerController()
{
Customer obj1 = new Customer();
obj1.Id = 12;
obj1.CustomerCode = "1001";
obj1.Amount = 90.34;
http://localhost/Customer/DisplayCustomerhttp://localhost/Customer/DisplayCustomerhttp://localhost/View/ViewCustomer/http://localhost/Customer/ViewCustomer/1001http://localhost/Customer/ViewCustomer/Shivhttp://localhost/Customer/ViewCustomer/Shivhttp://localhost/Customer/ViewCustomer/1001http://localhost/View/ViewCustomer/http://localhost/Customer/DisplayCustomer8/10/2019 Lap trinh MVC-Mvc Book
28/72
28Learn MVC step by step
Customers.Add(obj1);
obj1 = new Customer();
obj1.Id = 11;
obj1.CustomerCode = "1002";
obj1.Amount = 91;
Customers.Add(obj1);
}[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
}
The controller has a simple DisplayCustomer function which displays the customer using the id value. This function takes the
id value and looks up through the customer collection. Below is the downsized reposted code of the function.
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}If you look at the DisplayCustomer function it takes an id value which is numeric. We would like put a validation on thisid
field with the following constraints:-
Id should always be numeric.
It should be between 0 and 99.
We want the above validations to fire when the MVC URL is invoked with data.
Step 3:- Apply validation using regex on the MVC routes
The validation described in the step 2 can be achieved by
applying regular expression on the route map. If you go
to global.asax file and see the maproute function on the
inputs to this function is the constraint as shown in the
below figure.
So in order to accommodate the numeric validation we need to the specify the regex constraint i.e. \d1,2- in the maproute
function as shown below. \d1,2- in regex means that the input should be numeric and should be maximum of length 1 or 2 ,
i.e. between 0 to 99.
You can specify default values by saying id=0 as shown in the below code snippet. So just in case if someone does not specify
the value to the id it will take the value as zero by default.
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id =
@"\d{1,2}" }); // Parameter defaults
Step 4:- Test if it worksSo now that we are done with the validation using the maproute
functions, its time to test if these validations work.
So in the first test we have specified valid 1 and we see that the
controller is hit and the data is displayed.
8/10/2019 Lap trinh MVC-Mvc Book
29/72
29Learn MVC step by step
If you try to specify value more than 100 you woul d get error as shown below. Please note that the error is confusing but its
the effect of the regex validation which is specified on the maproute function.
If you try to specify a non-numeric value you should again get the same error which confirms that our regex validation is
working properly.
The most important point to note is that these validations are executed even before the request reaches the controllerfunctions.
Lab 10:- Partial views
When we talk about web application reusability is the key. So as a MVC developer we would like
to create reusable views. For instance we would like to create reusable views like footer and
header views and use them inside one big MVC view.
Reusable views can be achieved by creating Partial views.
Step 1:- Create a simple view with controller
The first step would be to create a simple view with a controller. You can seefrom the below snapshot, I have created a simple view called as Index.aspx
which will be invoked via Homecontroller.cs.
Step 2:- Create a simple partial view
Now that we have created the main view its time to create a partial view
which can be consumed inside the Index view. In order to create a partial
view , right click on the view folder and mark the check box Create a partial
view as shown in the below figure.
Step 3:- Put something in partial view
Put some text or logic in your partial view.
This is reusable view
Step 4:- Call the partial view in the main
Finally call the partial view in the main view using Html.RenderPartial function and pass the view name in the function as
shown in the below code snippet.
Also ensure that the partial view is in the same folder where your main view is. In case its not then you need to also pass the
path in the RenderPartial function. You can see in the below figure I have moved the partial view in the main Views folder.
8/10/2019 Lap trinh MVC-Mvc Book
30/72
30Learn MVC step by step
Step 5:- Run the program and see the action.
Finally do a CNTRL + f5, put the proper controller path and see your hard work
result. Below is the snapshot of how things should look like.
Lab 11:- Validation using Data Annotation
Validating data is one of the key things in any web application. As a developer you would like to run validation both on the
client side (browser) and also on the server side.
So you would probably like to write the validation once and then expect the validation framework to generate the validation
logic on both the ends.
Good news, In MVC this is possible by using data annotations.
In MVC you validate model values. So once the data comes inside the model you would like to question the model saying, is the
data provided proper? Are values in range? etc.
Data annotations are nothing but the metadata which you can apply on the model and the MVC framework will validate using
the metadata provided.
In this lab lets enforce validation by using data annotation. So the first thing is use Lab 4 and create a simple model and a
strong typed data entry view.
So assuming you have created the model and the strong typed view, lets start applying data annotations.
Note: - The view created should be a strong typed view.
Step 1:- Decorate model with data annotation
Import the data annotation namespace as shown in the code snippet below.
using System.ComponentModel.DataAnnotations;
Let say we have a customer model and we want to ensure that the customer code field is compulsory. So you can apply
attribute Required as shown in the below code snippet. If the validation fails and you would like to display some error
message, you can pass the ErrorMessage also. public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
Step 2:- Change the ASPX code
Now there are some code changes we would be doing in the ASPX code as compared to our previous lab. Inside the body we
would like to display error message if the data is not proper. This is done by using the below code snippet.
We also need to our HTML form to input data. Below is the code snippet for the same
m.CustomerCode)%>
m.CustomerCode)%>
8/10/2019 Lap trinh MVC-Mvc Book
31/72
31Learn MVC step by step
Step 3:- Enable Client validation
As said previously we would like to fire validation on both server and client side. In order to fire validations on the client side,
we need to refer three JavaScript files as shown in the below code snippet.
Also note the call to EnableClientValidation method due to which client side validations are enabled.
Step 4:- Write your controller logic
From the UI when the form calls a post on the controller, you would like to know if the model state is proper or not. This can be
done by checking the ModelState.IsValid property. So if this property is valid then call the save method and call the thanks
view or else go back to the customer view.
[HttpPost]
public ActionResult PostCustomer(Customer obj)
{ if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Step 5:- Run your application to see the action
Finally run your application and see the data annotation in action.
Summary of other data annotation attributes
There are other data annotation attributes which makes complex validation a breeze. Below are list of some of them:-
If you want to check string length, you can use StringLength.
[StringLength(160)]
public string FirstName { get; set; }
In case you want to use regular expression, you can use RegularExpression attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the Range attribute.[Range(10,25)]
public int Age { get; set; }
Some time you would like to compare value of one field with other field, we can use the Compare attribute.
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }
8/10/2019 Lap trinh MVC-Mvc Book
32/72
32Learn MVC step by step
In case you want to get a particular error message, you can use the Errors collection.
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the obj ect
is valid or not.
TryUpdateModel(NewCustomer);
In case you want add errors in the controller you can use AddModelError function.
ModelState.AddModelError("FirstName", "This is my server-side error.");
Lab 12:- MVC 3:- Razor
Change is a part of human life and same stands true for MVC as well.In this lab we will leave Aspx view engine in the behind
and start with razor,
In case you have not installed MVC 3 template, you can get it
fromhttp://www.asp.net/mvc/mvc3
Developers demanded for a clean, light weight view and with less
syntactic noise: - Answer was RAZOR.
So lets create a simple lab to demonstrate use of Razor views.
Step 1:- Install MVC 3 and create a project using the same
Install MVC 3 template fromhttp://www.asp.net/mvc/mvc3and create a project selecting the MVC 3 template below.
Step 2:- Select Razor
The next screen which pops up what kind of application you want to create.
The Empty option creates a project with least amount of files.
The Internet Application option creates a shell application which
includes user registration and authentication, navigation, and a
consistent visual style.
The Intranet Application option is very much same as Internet
Application with the only difference that the authentication takes place
through domain/Active Directory infrastructure.
For now lets keep life simple and lets select the empty option. The
second thing which we need to select is what kind of view we want, so
lets select Razor and move ahead.
Once the project is created you can see the Razor file with the name .cshtml. Now the
_ViewStart page is nothing but its a common page which will be used by views for
common things like layouting and common code.
http://www.asp.net/mvc/mvc3http://www.asp.net/mvc/mvc3http://www.asp.net/mvc/mvc3http://www.asp.net/mvc/mvc3http://www.asp.net/mvc/mvc38/10/2019 Lap trinh MVC-Mvc Book
33/72
33Learn MVC step by step
Step 3:- Add a view and invoke the same from controller.
Now go ahead and add a new view and invoke this view from the
controller. Adding and invoking the view from controller remains same as
discussed in the previous labs. Just remember to select the view as Razor
view.
public class StartController : Controller
{
//
// GET: /Start/
public ActionResult Index()
{
return View("MyView");
}
}
Step 4:- Practice Razor syntaxes
Now that we have the basic project and view ready lets run through some common razor syntaxes and try to get a feel how
easy RAZOR is as compared to ASPX views.
Practice 1:- Single line code
If you want to just display a simple variable you can do something as shown below. All razor syntaxes start with @. If you have
just single line of code you do not need . Razor figures out the ending logically.
Todays date @DateTime.Now
If you compare the above syntax with ASPX view you need to type the below code, so isnt
the syntax much simpler, neat and light weight.
Practice 2:- Multiple lines of code
If you have multiple line of code you can use @ followed by as shown in the below code snippet.
@{
ListMyCollections = new List();
obj.Add("Mumbai");
obj.Add("Pune");
obj.Add("Banglore");
obj.Add("Lucknow");
}
Practice 3:- For each loop and IF conditions
For loops and if conditions again become simpler as shown in the below lines of code.
@foreach (string MyString in MyCollections){
@MyString
}
@if (DateTime.Now.Year.Equals(2011))
{
// Some code here
}
8/10/2019 Lap trinh MVC-Mvc Book
34/72
34Learn MVC step by step
Practice 4:- Do not worry about @
If you are thinking that razor will get confusedbetween@ of Razorand @ of your email addressthen you are wrong. For
example in the below code razor will execute first line as a code and second line as an email address.
@DateTime.Now
Practice 5:- To display @
In case you want to display @ just type it twice as shown in the below code snippet the display will be something as shown in
the image below.
Tweet me @@Shivkoirala
Practice 6:- HTML display with razor
In case you want to display HTML on the browser. For instance below is a simple variable called as link which has HTML code? I
am displaying the variable data on the browser.
@{
var link = "Click here";
}
@link;If you execute the above code you would be surprised to see that it does not
display as HTML but as a simple display as shown below. Now thats not what
we expect? , we were expecting a proper HTML display. This is done by razor
to avoid XSS attacks (I will discuss about the same in later sections).
But no worries razor team has taken care of it. You can use the Html.Raw to display the same as shown in the below code
snippet.
@{
var link = "
Click here";
}
@Html.Raw(link);
Lab 13:- MVC Security Windows
Authentication)
Security is one of the most important things in any
application irrespective you develop them in any
technology, same holds true from MVC.
Before we start this lab one thing we need to understand
that MVC at the end of the day stands on ASP.NET
engine. In other words MVC uses the same security
methods which are applicable for ASP.NET i.e. Windows
and Forms authentication.
Now one way to implement windows authentication is by creating project using the intranet application option. As said
previously intranet application option is enabled to authenticate users from windows active directory.
For now we will not use the empty application option and create from scratch so that we can understand better.
Step 1:- Enable Windows Authentication
Once you have created the project the first step is to go and enable windows authentication using the and
tag as shown below.
8/10/2019 Lap trinh MVC-Mvc Book
35/72
35Learn MVC step by step
Step 2:- Just some defects
In MVC 3 template there is a small defect. It runs the forms authentication by default. Set the below tags in appsettings tag to
avoid problems. It took me 2 hours to figure this out, what a waste.
Step 3:- Apply Authorize tags on your controllers / actions.
Once you have enabled windows authentication use the *Authorize+ tag and specify which users can have access to the
controllers and actions. You can also specify roles if you wish.[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
Please note the user should be present in your windows AD or local
user group. Like in my case Administrator is present in my local
windows user group.
Step 4:- Create setup
Now its times to go and publish this solution on IIS so that we can test if
windows authentication works. In order to do the same we need to have
the necessary MVC DLLs also posted to the server. So right cl ick on the
project and select Add deployable dependencies.
In the next screen its will prompt which dependencies you want to include.
For now I have razor view so I
have selected both the
options.
Once you can see the dependent DLLs been added to the project.
8/10/2019 Lap trinh MVC-Mvc Book
36/72
36Learn MVC step by step
Step 5:- Create IIS application
Next step is to create an IIS application with only windows authentication enabled as shown in the figure.
Step 6:- Publish
Once you have created the IIS application, its time to publish your
application to the web application folder. So click on build and publish
as shown in the below figure. I have used File system as the publishmethod, you can use your choice.
Step 7:- Run the controller and action
Finally run the controller and action and see how windows authentication box pops up for User Name and Password.
If credentials are entered appropriately you should be able to see the
view.
Lab 14:- MVC Security Forms Authentication)
In the previous lab we saw how to do windows authentication. Windows authentication is great for intranet websites. But as
soon as we talk about internet websites, creating and validating users from Windows ADS / work groups is not a feasible option.
So in those kind of scenarios Forms authentication is the way to go.
Step 1:- Define the Login page controller
The first thing we need to do is define the controller which will invoke the login view. So I have created a simple index actionwhich invokes a view called as Index. This index view will take inputs like username and password.
public ActionResult Index()
{
return View();
}
8/10/2019 Lap trinh MVC-Mvc Book
37/72
37Learn MVC step by step
Step 2:- Create the index view
The next step is to create the login form which will take User Name and Password. To create the form we have used razor view
and the HTML helper classes.
This HTML form is making a post to the action Login which is currently in Home controller and its using HTTP POST method.
So when the user presses submit, it will hit the Login action. The next thing after this is to create the Login action which will
validate the username and password.
@{Html.BeginForm("Login", "Home", FormMethod.Post);}
User Name :- @Html.TextBox("txtUserName")
Password :- @Html.TextBox("txtPassword")
@{ Html.EndForm(); }
Step 3:- Validate credentials
In the login action the first thing we need to do is check if the user is proper or not. For now I have hardcoded the validation of
username and passwords. This can always be replaced by querying from SQL Server or from some other source.
if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123"))
{
..
}
Once we have checked the credentials the next step is to use the famous FormsAuthentication class and set the cookie saying
that this user is proper.
So that in the next request when the user comes he will not be validated again and again. After the cookie is set redirect to the
About view or else just stand on the Index view.
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",true);
return View("About");
}
else
{
return View("Index");
}
}
My about view is just a simple page as shown below.
@{
Layout = null;
}
About
This is About us
8/10/2019 Lap trinh MVC-Mvc Book
38/72
38Learn MVC step by step
Step 4:- Authorize attribute
We also need to use put the *Authorize+ attribute on controllers which we want to restrict from unauthorized users. For
instance you can see in the below code snippet, Default and About actions are decorated using *Authorize+ attribute.
So if any user who is unauthorized, directly hits any one of these controllers they will be sent back to the Index view i.e. backto Login screen.
[Authorize]
public ActionResult Default()
{
return View();
}
[Authorize]
public ActionResult About()
{
return View();
}
Step 5:- Change Web.config file
Finally we need to make the famous change in the web.config,i.e. Enabling Forms security. The most important part in the
below code snippet to note is the LoginUrl property.
Normally in ASP.NET this login URL points to an ASP.NET page, but in MVC it points to an action i.e. /Home/Index. This action
invokes the login credentials page.
Step 6:- See Forms authentication in action
With those above 5 steps you are now completely ready to go. If you now tryto call the About action directly, it will show up the below screen. This test
proves that Forms authentication is working. It has automatically detected
that the user is not valid and redirected the same to the Index action which
further invoked the Login form.
Lab 15:- JSON, MVC and JQuery
So in this lab we will expose a simple Customer object from MVC in JSON format and
consume the same using JQuery.
For this lab please ensure that the project is created by using basic project template so
that the necessary JQuery libraries are included with the MVC project.
Step 1:- Create a simple Customer model
So the first step is to create a simple Customer class in the MVC project.
public class Customer
{
private string _CustomerCode;
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
8/10/2019 Lap trinh MVC-Mvc Book
39/72
39Learn MVC step by step
}
Step 2:- Expose Customer object as JSON
To expose the customer object in JSON format we need to use JsonResult as shown in the below code snippet.
public JsonResult getJson()
{
Customer obj = new Customer();obj.CustomerCode = "c001";
return Json(obj,JsonRequestBehavior.AllowGet);
}
Please do once run the controller with the above JSON action to check if
the JSON result is displayed properly. If you are using chrome the display
comes on the browser, if its internet explorer it spits out a file.
Step 3:- Consume the JSON controller in jQuery
In case you are new to jQuery, please read thiswhat is jQuery?
The next step is to consume the JSON data in jQuery using MVC view. So go ahead and add a view for example my view name is
LearnJquery.aspx.
First thing add the jQuery library at the top of the ASPX page. In case you do not find jQuery library in your project that meansyou have not created the MVC project using the basic template.
You can then make a call the controller which is exposing in JSON format using getJson method as shown below. Its takes
three parameters:-
The first parameter in getJson is the MVC JSON URL with complete controller/action path format.
The second parameter is the data to be passed. For now itsNULL as we are more interesting in getting JSON data
rather posting data.
The last parameter is the call back method (Display) which will be invoked once we get the JSON data from the
controller. The Display function is also available in thebelow code snippet. I am just putting an alert with the
property name. FYI you can see how I have just typed data.CustomerCode , no parsing nothing the JSON data is
automatically translated to javascript object.
$.getJSON("/Json/getJson", null, Display);function Display(data)
{
alert(data.CustomerCode);
}
The complete MVC view HTML looks as shown below. I have created a simple HTML button and on the click event I am calling a
getJson JavaScript method which makes a call to the JSON controller and displays the JSON data in a JavaScript alert.
function getJson() {
$.getJSON("/Json/getJson", null, Display);
return true;
}
function Display(data)
{
alert(data.CustomerCode);
}
This view I have invoked by using DisplayJson action.
public class JsonController : Controller
{
public ActionResult DisplayJson()
{
http://www.dotnetinterviewquestions.in/article_what-is-jquery-aspnet-jquery-interview-questions-with-answers_154.htmlhttp://www.dotnetinterviewquestions.in/article_what-is-jquery-aspnet-jquery-interview-questions-with-answers_154.html8/10/2019 Lap trinh MVC-Mvc Book
40/72
40Learn MVC step by step
return View("LearnJquery");
}
}
Step 4:- Run the application and see the data
After you have done all the hardwork its time to hit the DisplayJson action to see the beauty running.
Lab 16:- Session management in MVC ViewData,ViewBag,TempData and session variables)
The primary goal of MVC is to create web applications and web applications use HTTP protocol. Now HTTP protocol is a
stateless by nature. So when you send a request to MVC application it serves the request and forgets about the request. Next
time when the same user sends the request MVC treats that as a complete new request.
Now think about the below situation:-
End user sends request to a MVC site.
MVC sends a login page.
User enters proper details and sends data to the MVC application.
MVC validates the user and sends home page of the site. MVC application now forgets everything about the user as
its stateless.
Now user clicks on one of the home page links. This is sent to the MVC application and because MVC application has
forgotten everything about the user, he sends a login page again for authentication.User would feel Weird
In short we need to have some kind of mechanism which will help us to remember states between request and response of
MVC.
There are 3 ways of maintaining states in MVC and these ways can be used depending from which layer to which layer you
navigate.
Temp data: - Helps to maintain data on redirects for a single request and
response. Now the redirects can be from controller to controller or from
controller to view.
View data: - Helps to maintain data when you move from controller to view.
View Bag: - Its a dynamic wrapper around view data.
When you use Viewbag type casting is not required. It
uses the dynamic keyword internally.
Session variables: - By using session variables we can maintain data until the browser closes.
Lets demonstrate the above fundamental with a demo.
8/10/2019 Lap trinh MVC-Mvc Book
41/72
41Learn MVC step by step
Step 1:- Create two controllers DefaultController1 and DefaultController2.
Add two controllers DefaultController1 and DefaultController2.
Step 2:- Set Session,tempdata, viewdata and viewbag
In the Default1Controller in Action1 we set session,tempdata,viewdata and viewbag values as shown in the below code
snippet. Once we set the values we do a redirect to the action SomeOtherAction which belongs to Controller2.
public class Default1Controller : Controller{
// GET: /Default1/
public ActionResult Action1()
{
Session["Session1"] = "UntilBrowserCloses";
TempData["FortheFullRequest"] = "FortheFullRequest";
ViewData["Myval"] = "ControllertoView";
ViewBag.MyVal = "ControllertoView";
return RedirectToAction("SomeOtherAction","Default2");
}
}
Step 3:- Read Session, tempdata , viewdata and viewbag values
In Default2Controller we will try to read values set in Default1Controller. Once the values are read we invoke a view cal ledas SomeView.
Please note I am setting ViewData and ViewBag before redirecting to the view.
public class Default2Controller : Controller
{
// GET: /Default2/
public ActionResult SomeOtherAction()
{
string str = Convert.ToString(TempData["FortheFullRequest"]);
string str2 = Session["Session1"].ToString();
string str3 = Convert.ToString(ViewData["Myval"]);
ViewData["Myval"] = "ControllertoView";
ViewBag.MyVal = "ControllertoViewCollection";
return View("SomeView");
}}
The SomeView view just displays the data present in TempData ,ViewData , ViewBag and Session .
Click
So lets put debug points in both the controller actions and lets hit
Default1 controller and Action1 action
http://localhost:1203/Default1/Action1 . So in this action session,
tempdata , viewdata and viewbag are loaded. Below is how the
watch window looks with data.
Now from here we are redirecting to controller2 action
SomeOtherAction.
http://localhost:1203/Default1/Action1http://localhost:1203/Default1/Action18/10/2019 Lap trinh MVC-Mvc Book
42/72
42Learn MVC step by step
In controller2 you can see get TempData and
Session variables but not ViewBag and ViewData
(See str3 and str4 are set to null). In other words
ViewData and ViewBag do not persist data in
redirects while TempData and Session variables do.
I have set ViewData and ViewBag with some dataagain before invoking the view SomeView.
When the view gets invoked we can see all the data. In
other words ViewData and ViewBag persist data from
controller to view. And also tempdata and session have
persisted data.
As you can see in the view we have a simple hyper link which will invoke
ActionNew in ControllerNew action.
When we click on
the link. All the other variables go off only session variables persist,
see the below figure. It means Session variables can persist
between requests
Below is a summary table which shows different mechanism of persistence.
Maintains data between ViewData/ViewBag TempData ( For single request) Session
Controller to Controller No Yes Yes
Controller to View Yes Yes Yes
View to Controller No No Yes
Lab 17:- Asynch controllers
MVC applications at the end of the day are web applications which are hosted
inside IIS.Now when any request comes to MVC controller it pulls up a thread
from thread pool and serves that request. In other words IIS web server
maintains a pool of threads rather than creating threads from scratch again and
again to gain performance benefits.
Lets assume that a web server has a thread pool size of 2. Now this is just an
assumption because a pool size of two is very much hypothetical. But to make
things simple consider that the thread pool size is 2.
So lets say first request comes to the site, IIS pulls up a readymade thread object from the thread pool and starts serving that
request. In the meantime lets say second request comes in so again IIS pulls up a thread from the thread pool and starts
serving the second request.
Now the fun starts when third request comes in. The IIS webserver does not have any more thread objects in the pool as those
are already serving request1 and request2. So he just moves the third request in to a waiting mode or the server can send
503 busy message to the client.
8/10/2019 Lap trinh MVC-Mvc Book
43/72
43Learn MVC step by step
This situation is termed as Thread Starvation. Thread starvation situations can be overcome by making the request
Asynchronous. So the request comes in and immediately the request is processed in an Asynch manner and releasing the
thread serving the request immediately.
So to avoid this we can achieve the same by making our controllers Asynch.
Note:Please watch the video from DVD and learn more about MVC Thread starvation.
So lets understand step by step how to implement MVC Asynch controllers.Step 1:- Inherit from AsyncController class
Consid