Learn MVC Project in 7 Days PDF
Learn MVC Project in 7 Days PDF
Day 1 is kind of a warm up. In this first day we will understand Why MVC over WebForms? , Issues with
WebForms and we will do two Lab’s one around controller and the around views.
After each one of these lab’s we will run through a small Q and A session where we will discuss concepts
of the lab. So the structure of this is article is Lab’s and then Q and A.
In case for any Lab you have questions which are not answered in the Q and A please feel free to put the
same in the comment box below. We will definitely answer them and if we find those question’s
recurring we will include the same in the article as well so that rest of the community benefit from the
same.
So we just need your 7 day’s and rest this article assures you become an ASP.NET MVC developer.
We just need Visual Studio and the good news is that visual studio is completely free. You can download
SUKESH MARLA 1
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Visual studio community edition from http://www.visualstudio.com/ , no expiry , no license issues and
you do not need deep pockets.
“You are reading this article because you know ASP.NET and you want to upgrade yourself to MVC.”
Sorry for the trouble, can you please read the above statement again and if you think its right then this
section is a must read for you.
Lot of ASP.NET developers who start MVC for the first time think that MVC is different new, fresh from
ASP.NET. But the truth is ASP.NET is a framework for creating web application while MVC is a great
architecture to organize and arrange our code in a better way. So rather than MVC you can say ASP.NET
MVC.
Ok so if the new thing is ASP.NET MVC what is the old thing called as, it’s “ASP.NET WebForms”.
“You are reading this article because you know ASP.NET WebForms and you want to upgrade yourself to
ASP.NET MVC.”
So now that your vocabulary is corrected welcome to the world of ASP.NET MVC and let’s start this
tutorial.
ASP.NET WebForms has served and successfully delivered web application for past 12 years. Let us try to
understand the secret of what made WebForms so popular and successful.
If you see the success of Microsoft programming languages right from the days of VB (visual basic) it is
due to RAD (Rapid application development) and visual programming approach. Visual programming
was so much preached and successful in Microsoft that literally they named their IDE as “Visual studio”.
SUKESH MARLA 2
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
By using visual studio, developers where able to drag drop UI elements on a designer area and at the
backend, visual studio generates C# or VB.NET code for those elements. These codes where termed as
“Behind Code” or “Code Behind”. In this code behind Developers can go and write logic to manipulate
the UI elements.
So the visual RAD architecture of Microsoft has two things one is the UI and the other is the code
behind. So for ASP.NET Web forms you have ASPX and ASPX.CS, for WPF you have XAML / XAML.CS and
so on.
So when ASP.NET WebForms was so successful, why Microsoft thought of creating Asp.Net MVC. The
main problem with ASP.NET WebForm is performance, performance and performance. In web
application there are two aspects which define performance:-
Let us try to understand why response time is slower when it comes to ASP.NET WebForms. We did a
small load testing experiment of WebForm vs MVC and we found MVC to be twice faster.
Let us try to understand why ASP.NET MVC was better in performance in the above load test. Consider
the below simple UI code and Code behind for that UI.
Assume the ASPX code has the below simple text box.
In the code behind you have written some logic which manipulates the text box values and the back
ground color.
SUKESH MARLA 3
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
If you see the HTML output by doing view source it looks something as shown below.
<input name="TextBox1" type="text" value="Make it simple" id="TextBox1" style="background-
color:Aqua;" />
Now stop reading for a moment, close your eyes and think. Try to get answers to the below questions:-
1. Is this an efficient way of generating HTML? Do we really need to make those long server trips to
get those simple HTML on the browser?
2. Can’t the developer write HTML straight forward, is it so tough?
If you see for every request there is a conversion logic which runs and converts the server controls to
HTML output. This conversion gets worse and heavy when we have grids, tree view controls etc. where
the HTML outputs are complicated HTML tables. Due to this unnecessary conversion the response time
is less.
Solution for this problem: - “GET RID of CODE BEHIND”, fold your sleeves and work with pure HTML.
Bandwidth consumption
ViewState has been a very dear and near friend of ASP.NET developers for past 10 years because it
automatically saves states between post backs and reduces our development time. But this reduction in
development time comes at a huge cost, ViewState increases the page size considerably. In this load
test we found ViewState increases the page size twice as compared to simple ASP.NET WebForms.
Below is the plot of the content length emitted from WebForm and MVC.
SUKESH MARLA 4
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
The size increase is because of extra bytes generated from ViewState, below is the snapshot of a
ViewState. Lot of people can argue that ViewState can be disabled but then we all know how developers
are, if there is option given they would definitely try that out.
Note: - The rest of the three points down below are brownie issues which have cropped up due to
presence of code behind and server controls. But the main thing is always performance.
HTML customization
Now because we are salves of the code behind and ASP.NET web server controls, we have “NO IDEA”
what kind of HTML can come out and how efficient they are. For example see the below ASPX code, can
you guess what kind of HTML it will generate.
Will Label generate DIV tag or SPAN tag? If you run the above code below are the respective generated
HTML. Label generates a SPAN, Literal generates simple text, and Panel generates DIV tag and so on.
SUKESH MARLA 5
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
So rather than generating HTML using server controls how about writing HTML directly and taking
complete control of HTML.
So the solution for this problem is “DO NOT USE SERVER CONTROLS” and work with direct HTML.
The other great benefit of working directly with HTML is that your web designers can work very closely
with the developer team. They can take the HTML code put in their favorite designer tool like
Dreamweaver, front page etc. and design independently. If we have server controls these designer tools
do not identify them easily.
Because the “WebForm” class cannot instantiate without “request” and “response” object. If you have
ever seen the “Button Click” events of “WebForm” they are as shown in the code below. From the code
you can know how difficult it is to instantiate the same.
Solution for this problem: - “GET RID of SERVER CONTROLS and CODE BEHIND”.
Unit Testing
As said in the previous section you cannot instantiate behind code straight forward it’s very difficult to
do unit testing or I will say automation testing on the code behind. Someone has to manually run the
application and do the testing.
SUKESH MARLA 6
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
The solution is we need to move the code behind to a separate simple class library and get rid of
ASP.NET Server controls and write simple HTML.
In short the solution should look something as shown in the below image.
This UI talk’s with .NET classes which you can term as middle layer, business logic etc. and the middle
layer talks with data access layer.
SUKESH MARLA 7
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
So MVC comprises of three sections Model, View and Controller. The code behind logic goes in to the
controller. View is your ASPX i.e. pure HTML and your Model is your middle layer. You can see in the
above diagram how those layers fit in.
So if you see there are two major changes VIEW becoming simple HTML and code behind moving to
simple .NET classes termed as controller.
Step 2:- Depending on the action controller creates the object of the model. Model in turn calls the data
access layer which fetches data in the model.
Step 3:- This data filled model is then passed to the view for display purpose.
Now that we have understood the different components of MVC let’s go in depth in to each one of
these components, let us start doing some labs. Let us first start with controllers as they are the most
important and central part of the MVC architecture.
SUKESH MARLA 8
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
By means of such request, client is trying to interact with server. Server is able to respond back because
some logic is written at server end to fulfill this request.
Scenario 2
It also possible that response sent by Server is an HTML response. HTML response which can consist of
couple of input controls and a submit button.
SUKESH MARLA 9
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
“In reality in web programming there is no concept of events. In case of Asp.Net Web Forms Microsoft
wrote some code on behalf of us and brought us the feeling of event driven programming. It’s just an
abstraction or the right word would illusion.”
When button is clicked a simple HTPP request is sent to the server. This time the difference is, values in
the “Customer Name”, “Address” and “Age” will be sent along with request. (In technical terms “values
are posted to the server”).
Ultimately, if it’s a request then there must be a logic written in the server so that server can send back
the response. In short there must be some user interaction logic written on the server.
In Asp.Net MVC, the last letter C that is Controller is the one who will handle the user interaction Logic.
Step 1.2 Select Web Application. Put Name. Put Location and say ok.
SUKESH MARLA 10
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Step 1.4 Click on Change Authentication. Select “No Authentication” from “Change Authentication”
dialog box and click ok.
SUKESH MARLA 11
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 12
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 1
What is the relationship between TestController and Test?
TestController is the class name whereas Test is the controller name. When you type the controller
name on the URL it should be without the word controller.
Note: In Asp.Net Web Forms default return response is always HTML. In case we want to return
something other than HTML (in Asp.Net Web Forms), we create HTTP handlers, override content type,
SUKESH MARLA 13
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
do response.end etc. It’s not an easy task. In Asp.Net MVC it’s very easy. If return type is ‘string’ you can
just return string , you do not need to send complete HTML.
When return type is some object like ‘customer’, it will return ‘ToString()’ implementation of that
object.By default ‘ToString()’ method returns fully qualified name of the class which is
“NameSpace.ClassName”;
SUKESH MARLA 14
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
When we try to make request to above action method we will get following response.
SUKESH MARLA 15
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Step 2.2. In the “Add View” dialog box put view name as “MyView”, uncheck “use a layout” checkbox
and click “Add”.
SUKESH MARLA 16
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MyView</title>
</head>
<body>
<div>
Welcome to MVC 5 Step by Step learning
</div>
</body>
</html>
Talk on Lab 2
Why View is placed inside Test Folder?
In Asp.Net MVC, Views associated with the particular controller is placed inside a special folder. This
special folder will be named as “ControllerName” and placed inside Views folder (located in the root
folder). For every controller only those views will be available which are located inside its own
folder.
For example: All the views related to Test controller will be placed inside “~/Views/Test” and Test
controller can access only those views which are inside Test folder.
SUKESH MARLA 17
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Views located inside this Shared folder will be available to all the controllers.
Is it possible that one action method is referencing more than one views?
Yes. Look at the following code.
public ActionResult GetView()
{
if(Some_Condition_Is_Matching)
{
return View("MyView");
}
else
{
return View("YourView");
}
}
Note: In MVC views and controllers are not tightly coupled. One action method can refer more than one
view and one view can be referred by more than one action method (by keeping them in Shared folder).
It provides better reusability
Note: In MVC 5 support for aspx view engine is removed. That’s why in “Add View” dialog box
there is no option to select the ViewEngine.
3. View Engine parses the server syntaxes in the view and creates in pure HTML response. Example
when it’s razor view engine, it understand razor syntaxes written in the view and parse it to pure
HTML string.
4. This HTML string will be returned to the end user.
Note: In the above example we have not used any razor syntaxes hence in this case ViewEngine just take
the View and return the same as it is.
What is ActionResult?
SUKESH MARLA 18
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
ActionResult encapsulates response of a user request. In Asp.Net MVC when end user makes a request
to an action method, action method may return ActionResult.
What is ViewResult?
HTML output retrieved from View function is ViewResult. In simple words it’s a result of view.
What is ContentResult?
ViewResult represents a complete HTML response whereas ContentResult represents a scalar text
response. It’s just like returning pure string. Difference is ContentResult is an ActionResult wrapper
around string result. ContentResult is also the child of ActionResult.
SUKESH MARLA 19
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Model
In Asp.Net MVC model represent the business data.
Note: Make sure to put using statement in the top or else we have to put fully qualified name of
employee.
SUKESH MARLA 20
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 3
What is the difference between writing Razor code with brace brackets (that is “{“ and “}”) and
without brace brackets?
In the last lab @emp.FirstName can be replaced with following code snippet.
@{
Response.Write(emp.FirstName);
}
@ Without brace brackets simply display the value of variable or expression.
SUKESH MARLA 21
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Just for demo purpose. In real time we will get it from may be database or wcf or web service or may be
from somewhere else.
What about the Database Logic/ Data Access Layer and Business Layer?
Data Access Layer is one of the unspoken layer in Asp.Net MVC. It’s always there but never
included in MVC definition.
Business layer as explained prior, it’s a part of Model.
Complete MVC structure
SUKESH MARLA 22
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 4
Can we pass ViewData and get it as ViewBag?
Yes, We can. Vice versa is also possible. As I said before, ViewBag is just a syntactic sugar for ViewData,
Performance issues
Values inside the ViewData are of type Object. We have to cast the value to correct type before using it.
It adds additional overhead on performance.
In MVC, controller and View are loosely connected to each other. Controller is completely unaware
about what’s happening in View and View is unaware about what’s happening in Controller.
From Controller we can pass one or more ViewData/ViewBag values. Now when Developer writes a
View, he/she have to remember what is coming from the controller. If Controller developer is different
from View developer then it becomes even more difficult. Complete unawareness. It leads to many run
time issues and inefficiency in development.
Let’s do a demo. This time we will take our View requirement to next level. If salary is greater than
15000 then it will be displayed in yellow colour or else green colour.
SUKESH MARLA 24
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 5
Is it required to type fully qualified class Name (Namespace.ClassName) in View every time?
No, we can put a using statement.
@using WebApplication1.Models
@model Employee
Is it must to make View a strongly typed view always or can we go with ViewData or ViewBag
sometimes?
As a best practice always make the view a strongly typed view.
Can we make our View a strongly typed view of more than one model?
No, we can’t. In real time project we often end up at a point where we want to display multiple models
in same view. Solution for this requirement will be discussed in next lab.
Other than these three issues, there is one more point worth discussion.
Let say we have situation where we want to display more than one kind of data in the View.
Example – Show Current logged in User’s Name along with Employee data
SUKESH MARLA 25
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
ViewModel a solution
ViewModel is one of the unspoken layer in the Asp.Net MVC application. It fits between Model and View
and act as data container for View
Create a new class called EmployeeViewModel inside ViewModels folder will looks like below.
SUKESH MARLA 26
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 27
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
vmEmp.SalaryColor="yellow";
}
else
{
vmEmp.SalaryColor = "green";
}
vmEmp.UserName = "Admin"
return View("MyView", vmEmp);
}
Same output as Lab 5 but this time View won’t contain any logic.
Talk on Lab 6
Does it means, every model will have one View Model?
No, Every View will have its corresponding ViewModel.
Should we always create ViewModel? What if View won’t contain any presentation logic and it want
to display Model data as it is?
We should always create ViewModel. Every view should always have its own ViewModel even if
ViewModel is going to contain same properties as model.
Let’s say we have a situation where View won’t contain presentation logic and it want to display Model
data as it is. Let’s assume we won’t create a ViewModel in this situation.
Problem will be, if in future requirement, if we have been asked to show some new data in our UI or if
we asked to put some presentation logic we may end with complete new UI creation from the scratch.
So better if we keep a provision from the beginning and Create ViewModel. In this case, in the initial
stage ViewModel will be almost same as Model.
SUKESH MARLA 28
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 29
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
In this lab, we will take our project to next level. We will add Business Layer to our project.
Create class called EmployeeBusinessLayer with a method called GetEmployees.
public class EmployeeBusinessLayer
{
public List<Employee> GetEmployees()
{
List<Employee> employees = new List<Employee>();
Employee emp = new Employee();
emp.FirstName = "johnson";
emp.LastName = " fernandes";
emp.Salary = 14000;
employees.Add(emp);
return employees;
}
}
SUKESH MARLA 30
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 7
Can we make View a strongly typed view of List<EmployeeViewModel>?
Yes, we can.
Why we create a separate class called EmployeeListViewModel, why didn’t we made View a strongly
typed view of type List<EmployeeViewModel>?
If we use List<EmployeeViewModel> directly instead of EmployeeListViewModel then there will be two
problems.
1. Managing future presentation logic.
2. Secondly UserName property. UserName is not associated with individual employees. It is
associated with complete View.
SUKESH MARLA 31
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 32
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 33
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Note: In above code snippet “TblEmployee” represents the table name. It automatically get created in
runtime.
Step 8 – Change Business Layer Code and get data from Database
Open EmployeeBusinessLayer class. Put using statement in the top.
using WebApplication1.DataAccessLayer;
SUKESH MARLA 34
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Right now we don’t have any employees in the database so we will see a blank grid.
Check the database. Now we have a table called TblEmployee with all the columns.
SUKESH MARLA 35
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Here we go
Talk on Lab 8
What is DbSet?
DbSet simply represent the collection of all the entities that can be queried from the database. When
we write a Linq query again DbSet object it internally converted to query and fired against database.
In our case “Employees” is a DbSet which will hold all the “Employee” entities which can be queried
from database. Every time we try to access “Employees” it gets all records in the “TblEmployee” table
and convert it to “Employee” object and return the collection.
Organize everything
Just to make everything organized and meaningful let’s do couple of changes.
Step 1 - Rename
“TestController” to “EmployeeController”
GetView action method to Index
Test folder (inside Views folder) to Employee
and “MyView” view to “Index”
SUKESH MARLA 36
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 37
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 9
What is the purpose of form tag?
In day 1 of the series we have understood that “Web world won’t follow Event driven programming
model. It follows request-response model. End user make the request and server sends response.”
Form tag is one of the way to make request in HTML. As soon as the submit button inside form tag gets
clicked, a request will be sent to the URL specified in action attribute.
How making request using Form tag is different from making request via browser address bar or
hyperlink?
SUKESH MARLA 38
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
When request is made with the help of Form tag, values of all the input controls are sent with the
request for processing.
What about checkbox, radio buttons and Dropdowns? Will values of this controls also sent?
Yes, All input controls (input type=text, type=radio, type=checkbox) and also dropdowns (which
represented as “Select” element).
SUKESH MARLA 39
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 10
How Textbox values are updated in Employee object inside action method?
In Asp.Net MVC there is a concept called as Model Binder.
Model Binder will executes automatically whenever a request is made to an action method
(action method which will contain parameter).
Model binder will iterate though all primitive parameters of a method and then it will compare
name of the parameter with each key in the incoming data (Incoming data means either posted
data or query string).When match is found, corresponding incoming data will be assigned to the
parameter.
After that Model binder will iterate through each and every property of each and every class
parameter and compare each property name with each key in incoming data. When match is
found, corresponding incoming value will be assigned to the parameter.
What will happen when two parameters are specified, one as “Employee e” and second as “string
FirstName”?
FirstName will be updated in both primitive FirstName variable and e.FirstName property.
SUKESH MARLA 40
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
...
<input type=”text” name=”FName”>
<input type=”text” name=”address.CityName”>
<input type=”text” name=”address.StateName”>
....
...
Note: Save button and Cancel button have same “Name” attribute value that is “BtnSubmit”.
SUKESH MARLA 41
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 11
Why same name is given to both Save and Cancel button?
We know that, as soon as submit button is clicked, a request is sent to the server. Along with the
request values of all the input controls will be sent.
Submit button is also an input button. Hence value of the submit button (which is responsible for the
request) will be sent too.
When Save button will be clicked, value of Save button that is “Save Employee” will be sent with request
and when Cancel button is clicked, value of Cancel button that is “Cancel” will sent with request.
In Action method, Model Binder will do remaining work. It will update the parameter values with values
in input data (coming with request)
SUKESH MARLA 42
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
</form>
Step 2 – Change Submit button to normal button and post above form with the help of
JavaScript.
<input type="button" name="BtnSubmit" value="Cancel"
onclick="document.getElementById('CancelForm').submit()" />
Why we have not used input type=reset for implementing Reset functionality?
Input type=reset control won’t clear the values, it just set the value to default value of a control.
Example:
<input type=”text” name=”FName” value=”Sukesh”>
In above example default value of control is “Sukesh”.
If we use input type=reset for implementing Reset functionality then by default “Sukesh” will be set in
the textbox every time “reset” button is clicked.
What if names are not matching with property names of the classes?
This is a very common question during interviews.
Let say we have HTML as follows
First Name: <input type="text" id="TxtFName" name="FName" value="" /><br />
Last Name: <input type="text" id="TxtLName" name="LName" value="" /><br />
Salary: <input type="text" id="TxtSalary" name="Salary" value="" /><br />
Now our Model class contain property names as FirstName, LastName and Salary. Hence default model
binder won’t work here.
In this situation we have following three solutions
Inside action method, retrieve posted values using Request.Form syntax and manually construct
the Model object as follows.
SUKESH MARLA 43
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 44
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
It generates RedirectToRouteResult Just like ViewResult and ContentResult (discussed in Day 1),
RedirectToRouteResult is a child of ActionResult. It represents the redirect response. When browser
receives RedirectToRouteResult, it makes new request to new action method.
Note: Here browser is responsible for new request hence URL will get updated to new URL.
What is EmptyResult?
One more child of ActionResult. When browser receives EmptyResult as a response it simply displays
blank white screens. It simply represents “No Result”.
In our example this situation won’t happen. Just to make sure that all code paths returns a value
EmptyResult statement was written.
Note: When ActionMethod return type is Void, it is equivalent to EmptyResult.
SUKESH MARLA 45
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Before we get into Data Annotation lets understand few more things about Model Binder
SUKESH MARLA 46
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 47
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
}
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}
Note: As you can see, When ModelState.IsValid is false response of SaveEmployee button click is
ViewResult pointing to “CreateEmployee” view.
<tr>
<td>
Salary:
</td>
SUKESH MARLA 48
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<td>
<input type="text" id="TxtSalary" name="Salary" value="" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("Salary")
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="BtnSubmit" value="Save Employee" />
<input type="submit" name="BtnSubmit" value="Cancel" />
<input type="button" name="BtnReset" value="Reset" onclick="ResetForm();" />
</td>
</tr>
</table>
Step 4 – Execute and Test
Press F5 and execute the application. Navigate to “Employee/AddNew” action method and test the
application.
Test 1
Test 2
SUKESH MARLA 49
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
To remove this error, simply add following statement in Application_Start in Global.asax file.
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesERPDAL>());
Database class exists inside System.Data.Entity namespace
Soon we are going to start a detail series on Entity Framework Code First approach where will speak
about this in detail. This article is intended to MVC and we are try to stick with it :)
Talk on lab 13
What does @Html.ValidationMessage do?
@ means it’s a razor code
Html is an instance of HtmlHelper class available inside view.
ValidationMessage is a function of HtmlHelper class which displays the error message
In Test 1 – we had kept salary as empty string. Now in this case, as per the Model binder explanation we
had (In Lab 13), ModelState.IsVaid will be false and ModelState will hold validation error related to
Salary which will displayed in view because of Html.ValidationMessage(“Salary”)
In Test 2 – Salary data type is mismatched hence validation is failed.
SUKESH MARLA 50
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Yes, Not only integers but all value types because they can’t hold null values.
SUKESH MARLA 51
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Test 2
SUKESH MARLA 52
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 53
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
vm.LastName = e.LastName;
if (e.Salary.HasValue)
{
vm.Salary = e.Salary.ToString();
}
else
{
vm.Salary = ModelState["Salary"].Value.AttemptedValue;
}
return View("CreateEmployee", vm); // Day 4 Change - Passing e here
}
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}
SUKESH MARLA 54
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Reason for above error will be discussed at the end of this lab. Let’s implement solution now.
Step 4 – Change AddNew Action method
public ActionResult AddNew()
{
return View("CreateEmployee”, new CreateEmployeeViewModel ());
}
Test 1
Navigate to the AddNew screen by clicking “Add New” link.
Keep First Name Empty
Put Salary as 56.
Click “Save Employee” button.
It will make two validations fail
Test 2
SUKESH MARLA 55
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see FirstName and LastName textbox values are maintained.
Talk on Lab 15
Are we really retaining values here?
No, we are not. Here we are actually repopulating the values from the posted data.
Why it’s required to pass “new CreateEmployeeViewModel ()” during initial request that is in “Add
New” action method?
In the View we are trying to populate textbox with the values in model.
Example:
<input type="text" id="TxtSalary" name="Salary" value="@Model.Salary" />
As you can see, in the above code block we are accessing FirstName property of current Model. If Model
is null, simply “Object reference not set to an instance of the class” exception will be thrown.
When “Add New” hyperlink is clicked, request will be handled by “Add New” action method. Earlier in
this action method we were returning view without passing any data. It means Model property inside
view be Null and Null. Something will throw “Object reference not set to an instance of the class”. To
solve this problems “new CreateEmployeeViewModel ()” was passed during initial request.
SUKESH MARLA 56
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
function IsFirstNameInValid() {
if (document.getElementById('TxtFName').value.indexOf("@") != -1) {
return 'First Name should not contain @';
}
else { return ""; }
}
function IsLastNameInValid() {
if (document.getElementById('TxtLName').value.length>=5) {
return 'Last Name should not contain more than 5 character';
}
else { return ""; }
}
function IsSalaryEmpty() {
if (document.getElementById('TxtSalary').value=="") {
return 'Salary should not be empty';
}
else { return ""; }
}
function IsSalaryInValid() {
if (isNaN(document.getElementById('TxtSalary').value)) {
SUKESH MARLA 57
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
if (FinalErrorMessage != "Errors:") {
alert(FinalErrorMessage);
return false;
}
else {
return true;
}
}
Step 3- Include Validation file in View
Simple put a reference of “Validations.js” file in the head section of “CreateEmployee” view as follows.
<script src="~/Scripts/Validations.js"></script>
SUKESH MARLA 58
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Test 1
Test 2
Talk on Lab 16
Why return keyword is required in onclick of SaveEmployee button click?
As we discussed in Lab 9, submit button will make a request to server when clicked. There is no point on
making server request when validation fails. By writing “return false” in the onclick of submit button, we
can stop the default server request.
In our case IsValid function will return false when validation fails and thus we achieve desired
functionality.
Instead of alert can we show the error messages in the page itself?
Yes we can. Simply create a span tag for each error. Make it invisible (using css) in the beginning and on
submit button click if validation fails make it visible using JavaScript.
SUKESH MARLA 59
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
In the Day 1 of this series we understood the real meaning of word Asp.net and MVC. We understood
that Asp.Net MVC is part of Asp.net. Most of the features of Asp.Net are inherited in Asp.Net MVC. One
of the feature is Forms Authentication.
Before we start with lab first let’s understand how Forms Authentication works in Asp.Net
1. End user make a request to Forms authentication enabled application with the help of browser.
2. Browser will send all the associated cookies stored in the client machine with request.
3. When request is received as server end, server examines the request and check for the special
cookie called “Authentication Cookie”.
4. If valid authentication cookie is found, server confirms the identity of the user or in simple
words, consider user as a valid user and make him go further.
5. If valid authentication cookie is not found server considers user as anonymous (or
unauthenticated) user. In this case if the requested resource is marked as protected/secured
user will be redirected to login page.
SUKESH MARLA 60
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<br />
@Html.LabelFor(c => c.Password)
@Html.PasswordFor(x => x.Password)
<br />
Example 2:
@using (Html.BeginForm("DoLogin", "Authentication", FormMethod.Post))
{
}
Above code will generate following HTML.
<form action="/Authentication/DoLogin" method="post">
</form>
SUKESH MARLA 61
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see, request to Index action automatically redirected to login action.
SUKESH MARLA 62
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 63
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Test 2
Talk on Lab 17
Why DoLogin is attached with HttpPost attribute?
This attribute makes DoLogin action method open for only Post request. If someone try to make a get
request to DoLogin it won’t work out.
SUKESH MARLA 64
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 65
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
By default cookieless property is set to “AutoDetect”. It means authentication works via cookies and in
case cookies are not supported URL will do the required work.
How come the UserName textbox is repopulated when credentials are wrong?
That’s the magic of HTML helper classes. They will repopulate the values in the controls from the posted
data. This is one of the advantage of using Helper classes.
Can we attach both HttpPost and Authorize attribute to same action method?
Yes we can.
SUKESH MARLA 66
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As per the discussion we had in Lab 6, View should not be connected to Model directly. We must always
have ViewModel in between View and Model. It doesn’t matter if view is a simple “display view” or
“data entry view”, it should always connected to ViewModel.
Reason for not using ViewModel in our project is simplicity. In real time project I strongly recommend
you to have ViewModel everywhere.
Controller Level
[Authorize]
public class EmployeeController : Controller
{
....
Global level
Step 1 - Open FilterConfig.cs file from App_start folder.
Step 2 - Add one more line RegisterGlobalFilters as follows.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());//Old line
filters.Add(new AuthorizeAttribute());//New Line
}
Step 3 - Attach AllowAnonymous attribute to Authentication controller.
[AllowAnonymous]
public class AuthenticationController : Controller
{
Step 4 – Execute and Test the application in the same way we did before.
SUKESH MARLA 67
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 68
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 69
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 70
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 71
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 21
How come client side validation is implemented?
As you can see, without much effort client side validation is implemented. In Login view, HTML elements
are generated using HTML helper classes. Helper functions while generating HTML markup attach some
attributes based on the data annotation attributes used.
Example:
@Html.TextBoxFor(x=>x.UserName)
@Html.ValidationMessageFor(x=>x.UserName)
Above code will generate following HTML.
<input data-val="true" data-val-length="UserName length should be between 2 and 7" data-val-length-
max="7" data-val-length-min="2" id="UserName" name="UserName" type="text" value="" />
<span class="field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true"> </span>
These custom HTML attributes will be used by “jQuery Unobtrusive validation files” and thus validation
get implemented at client side automatically.
Automatic client side validation is the second advantage of Html helper classes.
SUKESH MARLA 72
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Put View name as Footer, Check “Create as a partial view” checkbox and click “Add”.
Note: We already spoke about shared folder in Day 1. Shared folder contains views which will not be
specific to a particular controller. Views inside Shared folder will be available to all the controllers.
SUKESH MARLA 73
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 74
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Press F5. Navigate to Index view. (I believe, you know how to do it now.)
Talk on Lab 22
What does Html.Partial do?
Just like Html.RenderPartial, Html.Partial will be used to display Partial View in the View.
This is the syntax
@Html.Partial("Footer", Model.Footer Data);
Syntax is much simpler than earlier one.
What is MvcHtmlString and why does Html.Partial return MvcHtmlString instead of string?
First let’s understand what is MvcHtmlString?
As per MSDN “MvcHtmlString represents a HTML-encoded string that should not be encoded again”.
As you can see, razor displayed whole content as it is. Many people might have thought of seeing a bold
string but Razor Html encoded the content before displaying and that’s why instead of bold string we
got pure content.
We use MvcHtmlString when we don’t want razor to do the encoding. MvcHtmlString is an indication to
razor that “string is already encoded, no more encoding is required”.
For example look at the following code.
@{
string MyString = "<b>My Simple String</b>";
SUKESH MARLA 75
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
}
@MvcHtmlString.Create(MyString)
It will generate following output
Can’t we place Partial Views inside a specific controller folder, like Employee or Authentication?
We can do that but in that case it won’t be available to only specific controller.
Example: When we keep Partial View inside Employee folder it won’t be available for
AuthenticationController or to Views related to AuthenticationController.
What we said about reusability is completely true but what we said about execution is only true
logically. Technically it’s not a correct statement. We can create an action method which will return a
ViewResult as bellow.
public ActionResult MyFooter()
SUKESH MARLA 76
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
{
FooterViewModel Footer Data = new FooterViewModel();
Footer Data.CompanyName = "StepByStepSchools";//Can be set to dynamic value
Footer Data.Year = DateTime.Now.Year.ToString();
return View("Footer", Footer Data);
}
It will display following output
Although logically it doesn’t make sense, technically it’s possible. Footer.cshtml won’t contain properly
structured HTML. It meant to be displayed as a part of some other view. Hence I said “Logically it
doesn’t make sense”.
Why Partial View is created instead of putting footer contents directly in the view?
Two advantages
1. Reusability – we can reuse the same Partial View in some other View.
2. Code Maintenance – Putting it in a separate file makes it easy to manage and manipulate.
SUKESH MARLA 77
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 78
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 79
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<a href="/Authentication/Logout">Logout</a>
</div>
<hr />
@{
Html.RenderAction("GetAddNewLink");
}
<div>
<table border="1">
<tr>
Html.RenderAction executes the Action Method and writes result directly to response stream.
Test 2
Is it enough?
No, It not enough. What if a Non-Admin user directly try to navigate to AddNew action via URL.
SUKESH MARLA 81
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see in the above example, a Non-Admin user is able to access the AddNew action.
To solve this problem we will use MVC ActionFilters. Action Filters let us add some pre-processing and
post-processing logic to our action methods. In this lab we will look after pre-processing support of
ActionFilters and in coming up lab we will look into post-processing functionality as well.
SUKESH MARLA 82
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see, now your Action methods are completely secured.
SUKESH MARLA 83
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Note: Whatever strategy and logic we have used in this lab for implementing Role based security may
not be the best solution. You may have some better logic to implement such behaviour. It’s just one of
the way to achieve it.
Talk on Lab 23
Can we invoke GetAddNewLink directly via browser Address bar?
Yes, we already spoke about such behavior in “Talk on Lab 22” section.
What is ActionFilter?
Just like AuthorizationFilter ActionFilter is kind of Filter in Asp.Net MVC. It allows us to add pre-
processing and post-processing logic to action method execution.
Note: After each lab we are trying our best to cover each and every question a developer may come up.
In case you believe some more questions need to be included please free to send your questions to
[email protected]
SUKESH MARLA 84
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Before we go and start with our lab, first let’s discuss what all things we have to place in Layout Page
1. Header with Welcome Message
2. Footer with Footer Data
Biggest problem?
Data for Footer and Header is passed to view from Controller as a part of ViewModel.
Now the big question is, how data will be passed from View to Layout Page after header and footer are
moved to Layout Page.
Solution – Inheritance
We can simply follow the Object oriented Inheritance principle here. Let’s understand it with a lab.
SUKESH MARLA 85
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Remove UserName and Footer Data properties from EmployeeListViewModel class and inherit it from
BaseViewModel.
public class EmployeeListViewModel:BaseViewModel
{
public List<EmployeeViewModel> Employees { get; set; }
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
SUKESH MARLA 86
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<div>
@RenderSection("ContentBody")
</div>
@Html.Partial("Footer",Model.Footer Data)
</body>
</html>
As you can see we have created three sections in the layout page. TitleSection, HeaderSection and
ContentBody. Content pages will use these sections for defining appropriate contents.
Note: While defining HeaderSection second parameter is passed. This parameter decides whether it’s
the optional section or compulsory section. False indicates it’s an optional section.
@section TitleSection{
MyView
}
@section ContentBody{
<div>
@{
SUKESH MARLA 87
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Html.RenderAction("GetAddNewLink");
}
<table border="1">
<tr>
<th>Employee Name</th>
<th>Salary</th>
</tr>
@foreach (EmployeeViewModel item in Model.Employees)
{
<tr>
<td>@item.EmployeeName</td>
<td style="background-color:@item.SalaryColor">@item.Salary</td>
</tr>
}
</table>
</div>
}
As you can see, everything in the view is defined inside some section.
SUKESH MARLA 88
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Follow the same Step 7 procedure and define sections in CreateEmployee View. This time there will be
one addition. We will also define HeaderSection.
@section TitleSection{
CreateEmployee
}
@section HeaderSection{
<script src="~/Scripts/Validations.js"></script>
<script>
function ResetForm() {
document.getElementById('TxtFName').value = "";
document.getElementById('TxtLName').value = "";
document.getElementById('TxtSalary').value = "";
}
</script>
}
@section ContentBody{
<div>
<form action="/Employee/SaveEmployee" method="post" id="EmployeeForm">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" id="TxtFName" name="FirstName" value="@Model.FirstName" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("FirstName")
</td>
</tr>
<tr>
<td>
Last Name:
SUKESH MARLA 89
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
</td>
<td>
<input type="text" id="TxtLName" name="LastName" value="@Model.LastName" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("LastName")
</td>
</tr>
<tr>
<td>
Salary:
</td>
<td>
<input type="text" id="TxtSalary" name="Salary" value="@Model.Salary" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("Salary")
</td>
</tr>
<tr>
<td colspan="2">
SUKESH MARLA 90
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Index View was a strongly typed view of type EmployeeListViewModel which is a child of
BaseViewModel and that’s why it’s worked. CreateEmployee View is a strongly typed view of type
CreateEmployeeViewModel and it’s not the child of BaseViewModel and hence such error occurred.
SUKESH MARLA 91
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 92
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 25
What does RenderBody do?
When we first created in the Layout page it had one razor stamen something like below.
@Html.RenderBody()
Later we removed it and defined sections manually. Let’s understand what does it do?
In content pages we normally define sections which are declared in the Layout Page.
But a strange thing is, Razor allow us to define some contents outside the section too.
All the non-section contents in content page will be rendered by RenderBody function
Below image explains it better.
.
Can we have nested layouts?
Yes we can. We can create a layout page which will use some other layout page. Syntax will be same.
Is it required to put Header and Footer Data code in each and every Action Method?
No, it’s not required. We will make it reusable in next lab.
SUKESH MARLA 93
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Lab 26 – Making Header and Footer Data code more efficient with Action Filter
In Lab 23 we had seen one advantage of ActionFilter now it’s time for second.
SUKESH MARLA 94
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
}
}
}
OnActionExecuted will be used to add post processing logic to action method execution.
SUKESH MARLA 95
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
SUKESH MARLA 96
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
@model FileUploadViewModel
@{
Layout = "~/Views/Shared/MyLayout.cshtml";
}
@section TitleSection{
Bulk Upload
}
@section ContentBody{
<div>
<a href="/Employee/Index">Back</a>
<form action="/BulkUpload/Upload" method="post" enctype="multipart/form-data">
Select File : <input type="file" name="fileUpload" value="" />
<input type="submit" name="name" value="Upload" />
</form>
</div>
}
As you can see name of the property in FileUploadViewModel and name of the input [type="file"] are
same. It is “fileUpload”. We spoke on the importance of name attribute in Model Binder lab.
Note: In form tag one additional attribute that is enctype is specified. We will talk about it in the end of
the lab.
SUKESH MARLA 97
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
{
List<Employee> employees = new List<Employee>();
StreamReader csvreader = new StreamReader(model.fileUpload.InputStream);
csvreader.ReadLine(); // Assuming first line is header
while (!csvreader.EndOfStream)
{
var line = csvreader.ReadLine();
var values = line.Split(',');//Values are comma separated
Employee e = new Employee();
e.FirstName = values[0];
e.LastName = values[1];
e.Salary = int.Parse(values[2]);
employees.Add(e);
}
return employees;
}
AdminFilter attached to the Upload Action restrict access to Non-Admin user.
SUKESH MARLA 98
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 27
Why don’t we have validations here?
Adding client side and server side validation to this option will be an assignment for readers. I will give
you a hint.
For Server side validation use Data Annotations.
For client side either you can leverage data annotation and implement jQuery unobtrusive
validation. Obviously this time you have to set custom data attributes manually because we
don’t have readymade Htmlhelper method for file input.
Note: If you didn’t understood this point, I recommend you to go through “implanting client side
validation in Login view” again
For client side validation you can write custom JavaScript and invoke it on button click. This
won’t be much difficult because file input is an input control at the end of the day and its value
can be retrieved inside JavaScript and can be validated.
What is HttpPostedFileBase?
HttpPostedFileBase will provide the access to the file uploaded by client. Model binder will update the
value of all properties FileUploadViewModel class during post request. Right now we have only one
property inside FileUploadViewModel and Model Binder will set it to file uploaded by client.
SUKESH MARLA 99
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
2. Create multiple file input controls. Each control must have same name. Now instead of creating
multiple properties of type HttpPostedFileBase, create one of type List< HttpPostedFileBase>.
Note: Above case is true for all controls. When you have multiple controls with same name ModelBinder
update the property with the value of first control if property is simple parameter. ModelBinder will put
values of each control in a list if property is a list property.
When enctype="multipart/form-data" attribute is added to form tag, following post request will be sent
to the server.
POST /Authentication/DoLogin HTTP/1.1
Host: localhost:8870
Connection: keep-alive
Content-Length: 452
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarywHxplIF8cR8KNjeJ
...
...
------WebKitFormBoundary7hciuLuSNglCR8WC
Content-Disposition: form-data; name="UserName"
Admin
------WebKitFormBoundary7hciuLuSNglCR8WC
Content-Disposition: form-data; name="Password"
Admin
------WebKitFormBoundary7hciuLuSNglCR8WC
Content-Disposition: form-data; name="BtnSubmi"
10
SUKESH MARLA
0
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Login
------WebKitFormBoundary7hciuLuSNglCR8WC--
As you can see, form is posted in multiple part. Each part is separated by a boundary defined by
Content-Type and each part contain one value.
encType must be set to “multipart/form-data” if form tag contains file input control.
Note: boundary will be generated randomly every time request is made. You may see some different
boundary.
Although it’s the correct answer I was expecting a little different answer.
My question is what happen in the beginning.
10
SUKESH MARLA
1
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Worker thread will be blocked while the request is being processed and cannot serve another request.
Now let’s say an application receives too many requests and each request will take long time to get
completely processed. In this case we may end up at a point where new request will get into a state
where there will be no worker thread available to serve that request. This is called as Thread Starvation.
In our case sample file had 2 employee records but in real time it may contain thousands or may be lacks
of records. It means request will take huge amount of time to complete the processing. It may leads to
Thread Starvation.
Solution
Now the request which we had discussed so far is of type synchronous request.
Instead of synchronous if client makes an asynchronous request, problem of thread starvation get
solved.
In case of asynchronous request as usual worker thread from thread pool get allocated to serve
the request.
Worker thread initiates the asynchronous operation and returned to thread pool to serve
another request. Asynchronous operation now will be continued by CLR thread.
Now the problem is, CLR thread can’t return response so once it completes the asynchronous
operation it notifies Asp.Net.
Webserver again gets a worker thread from thread pool and processes the remaining request
and renders the response.
In this entire scenario two times worker thread is retrieved from thread pool. Now both of them may be
same thread or they may not be.
Now in our example file reading is an I/O bound operation which is not required to be processed by
worker thread. So it’s a best place to convert synchronous requests to asynchronous requests.
10
SUKESH MARLA
2
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see we have different thread id in the beginning and different in end.
Output is going to be same as previous lab.
So far we have spoken about two filters in Asp.Net MVC – Action Filters and Authorization Filters.
Now it’s time for third one – Exception Filters.
10
SUKESH MARLA
4
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
10
SUKESH MARLA
5
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<body>
<hgroup>
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
</hgroup>
</body>
</html>
Open FilterConfig.cs file from App_Start folder. In RegisterGlobalFilters method you will see that
HandleError filter is already attached at global level.
10
SUKESH MARLA
6
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
<body>
<hgroup>
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
</hgroup>
Error Message :@Model.Exception.Message<br />
Controller: @Model.ControllerName<br />
Action: @Model.ActionName
</body>
</html>
10
SUKESH MARLA
7
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
10
SUKESH MARLA
8
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Talk on Lab 29
Is it possible to change the view name?
Yes, it’s not required to keep view name as “Error” always.
In that case we have to specify view name while attaching HandlError filter.
[HandleError(View="MyError")]
Or
filters.Add(new HandleErrorAttribute()
{
View="MyError"
});
10
SUKESH MARLA
9
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
OR
filters.Add(new HandleErrorAttribute()
{
ExceptionType = typeof(DivideByZeroException),
View = "DivideError"
});
filters.Add(new HandleErrorAttribute()
{
ExceptionType = typeof(NotFiniteNumberException),
View = "NotFiniteError"
});
filters.Add(new HandleErrorAttribute());
In above case we are adding Handle Error filter thrice. First two are specific to exception whereas last
one is more general one and it will display Error View for all other exceptions.
}
}
Step 2 – Create EmployeeExceptionFilter class
Create a new class called EmployeeExceptionFilter inside Filters folder as follows.
namespace WebApplication1.Filters
{
public class EmployeeExceptionFilter
{
}
}
11
SUKESH MARLA
1
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Press F5 and execute the application. Navigate to Bulk Upload Option. Select above file and click on
Upload.
Output won’t be different this time. We will get a same Error View like before. Only difference will be
this time we will also find an error file created in “C:\\Errors” folder.
Talk on Lab 30
How come Error view is returned as a response when exception occurs?
In above lab we have overridden the OnException method and implemented exception logging
functionality. Now the question is, how come the default handle error filter is still working then?
It’s simple. Check the last line in the OnException method.
base.OnException(filterContext);
It means, let base class OnException do the reaming work and base class OnException will return
ViewResult of the Error View.
Routing
So far we have discussed many concepts, we answered many questions in MVC except one basic and
important one.
“What exactly happens when end user makes a request?”
Well answer is definitely “Action method executes”. But my exact question is how come controller and
action method are identified for a particular URL request.
Before we start with our lab “Implement User Friendly URLs”, first let’s find out answer for above
question. You might be wondering why this topic is coming in the ending. I purposely kept this topic at
near end because I wanted people to know MVC well before understanding internals.
Understand RouteTable
In Asp.Net MVC there is a concept called RouteTable which will store URL routes for an application.
In simple words it holds a collection defining possible URL patterns of an application.
By default one route will be added to it as a part of project template. To check it open Global.asax file. In
Application_Start you will find a statement something like below.
RouteConfig.RegisterRoutes(RouteTable.Routes);
You will find RouteConfig.cs file inside App_Start folder which contain following code block.
namespace WebApplication1
{
11
SUKESH MARLA
3
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
As you can see in RegisterRoutes method already one default route is defined with the help of
routes.MapRoute method.
Routes defined inside RegisterRoutes method will be used later in the Asp.Net MVC request cycle to
determine the exact controller and action method to be executed.
If it’s required we can create more than one route using route.MapRoute function. Internally defining
route means creating Route object.
MapRoute function also attach RouteHandler to route object which will be MVCRouteHandler in case of
Asp.Net MVC by default.
Step 1 – UrlRoutingModule
When end user make a request it first pass through UrlRoutingModule Object.
UrlRoutingModule is a HTTP Module.
Step 2 – Routing
UrlRoutingModule will get the first matching Route object from the route table collection.
Now for matching, request URL will be compared with the URL pattern defined in the route.
Following rules will be considered while matching.
Number of parameters in the requests URL(other than domain name) and in the URL pattern
defined in the route.
Example:
11
SUKESH MARLA
4
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
11
SUKESH MARLA
5
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Controller Name
In order to get the controller name from the request URL following simple rule is followed.
“In the URL pattern {controller} is the keyword to identify Controller Name”.
Example:
When URL pattern is {controller}/{action}/{id} and request URL is
“http://localhost:8870/BulkUpload/Upload/5”, BulkUpload will be name of the controller.
When URL pattern is {action}/{controller}/{id} and request URL is
“http://localhost:8870/BulkUpload/Upload/5”, Upload will be name of the controller.
Route Parameters
Basically a URL pattern can contain following four things
1. {controller} -> Identifies controller name
2. {action} -> Identifies action method name.
3. SomeString -> Example – “MyCompany/{controller}/{action}” -> in this pattern “MyCompany”
becomes compulsory string.
4. {Something} -> Example – “{controller}/{action}/{id}” -> In this pattern “id” is the route
parameter. Route parameter can be used to get the value in the URL itself at the time of
request.
Look at the following example.
Route pattern - > “{controller}/{action}/{id}”
Request URL -> http://localhost:8870/BulkUpload/Upload/5
Testing 1
11
SUKESH MARLA
6
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
11
SUKESH MARLA
7
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Now I believe you have good understanding the concept of Routing so let make our Project URLs more
user-friendly with the help of routing.
routes.MapRoute(
name: "Upload",
url: "Employee/BulkUpload",
defaults: new { controller = "BulkUpload", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
As you can see now we have more than one route defined.
(Default Route is kept untouched.)
11
SUKESH MARLA
8
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see URL is no more in the form of “Controller/Action”. Rather it is more user friendly but
output is same.
I recommend you to defines some more routes and try some more URLs.
Talk on Lab 31
Does earlier URL work now?
Yes, earlier URL will work too.
Now Index action in the BulkUploadController is accessible from two URLs
1. “http://localhost:8870/Employee/BulkUpload”
2. “http://localhost:8870/BulkUpload/Index”
11
SUKESH MARLA
9
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Is it a required to keep parameter name in action method same as Route Parameter Name?
Basically a single Route pattern may contain one or more RouteParameters involved in it.
To identify each route parameter independently it is must to keep parameter name in action method
same as Route Parameter Name.
In the above lab we have defined two routes. One custom route and one default route.
Now let say for an instance default route is defined first and custom route is defined second.
In this case when end user make a request with URL “http://.../Employee/BulkUpload” in the
comparison phase UrlRoutingModule finds that requested URL matches with the default route pattern
and it will consider “Employee” as the controller name and “BulkUpload” as the action method name.
Hence sequence is very important while defining routes. Most generic route should be kept at the end.
routes.MapMvcAttributeRoutes();
routes.MapRoute(
...
12
SUKESH MARLA
0
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
As you can see, we have same output but with different more User Friendly URL.
12
SUKESH MARLA
1
Learn MVC quickly and easily this Saturday and Sunday with our special “Learn MVC in
two days offline session”. For detail call us on 022-66752917
Conclusion
With Day 6 we have completed our sample MVC project. Hope you have enjoyed the complete series.
Day 7 will be there my friends. In day 7 we will create a Single Page Application using MVC, jQuery and
Ajax. It will be more fun and more challenge. Stay tuned
Your comments, Mails always motivates us do more. Put your thoughts and comments below or send
mail to [email protected]
12
SUKESH MARLA
2