MVC 2 is quiet old and this article was written long years back. We would recommend you to start reading from our fresh Learn MVC 5 step by step series from here: -http://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day
- So, what’s the agenda?
- Day 1: -Controllers, strong typed views and helper classes
- Day 2: - Unit test, routing and outbound URLS
- Day 3:- Partial views, Data annotations,Razor, Authentication and Authorization
- Day 4:- JSON, JQuery, State management and Asynch controller
- Day 5:- Bundling , Minification , ViewModels,Areas and Exception handling
- Day 6: - Display Modes,MVC OAuth,Model Binders,Layout and Custom view engine
- Lab 10: Partial views
- Lab 11: Validation using Data Annotation
- Lab 12: MVC 3: Razor
- Practice 1: Single line code
- Practice 2: Multiple lines of code
- Practice 3: Foreach loop and IF conditions
- Practice 4: Do not worry about @
- Practice 5: To display @
- Practice 6: HTML display with Razor
- Lab 13: MVC Security (Windows Authentication)
- Lab 14:- MVC Security (Forms Authentication)
- What’s for the fourth day?
- 50 MVC Interview questions with answers
- Are you completely new to MVC?
- Partial views.
- Validations using data annotations.
- Razor (MVC 3).
- MVC Windows authentication
- MVC Forms Authentication
- The Empty option creates a project with the 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 the same as Internet Application with the only difference that the authentication takes place through a domain/Active Directory infrastructure.
Introduction
So, what’s the agenda?
In Day 3 of learn MVC step by step we will look in do the following below 5 labs.
So let’s start with the above three labs one by one.
FYI: In case you are completely new to MVC (Model View Controller), please see the last section of the article for a kick start or can view other parts of MVC article as listed below:-
http://www.codeproject.com/Articles/207797/Learn-MVC-Model-view-controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-4
http://www.codeproject.com/Articles/667841/Learn-MVC-Model-view-controller-Step-by-Step-in-3
http://www.codeproject.com/Articles/724559/Learn-MVC-Model-view-controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/789278/Learn-MVC-Model-view-controller-Step-by-Step-in-d
Lab 10: Partial views
When we talk about web application, reusability is the key. So as an 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
The first step would be to create a simple view with a controller. You can see from the below snapshot, I have created a simple view called “Index.aspx” which will be invoked via “Homecontroller.cs”.
In case you are coming to this section directly, please see the previous Labs to synch up.
Step 2: Create a simple partial view
Now that we have created the main view, it’s 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 the partial view
Put some text or logic in your partial view.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
This is reusable view
Step 4: Call the partial view in the main
Finally call the partial view in the main view using the “Html.RenderPartial
” function and pass the view name in the function as shown in the below code snippet.
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
Also ensure that the partial view is in the same folder where your main view is. In case it’s 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.
One more thing which is noticeable is that the icons for main view and partial are very different. You can see the yellow border in the partial view icon which does not exist in the main view icon.
Step 5: Run the program and see the action
Finally do a CTRL + F5, put the proper controller path, and see your results. 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 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 ends. Good news, 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 metadata which you can apply on the model and the MVC framework will validate using the metadata provided.
In this lab let’s enforce validation by using data annotations. So the first thing is use Lab 4 and create a simple model and a strong typed data entry view. In case you have come to this lab straight, please have a look at day 1 labs before proceeding ahead.
So assuming you have created the model and the strong typed view, let’s 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's say we have a customer model and we want to ensure that the customer code field is compulsory. So you can apply the 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 the error message if the data is not proper. This is done by using the below code snippet.
<%= Html.ValidationSummary() %>
We also need to code our HTML form to input data. Below is the code snippet for the same. Please note, the “EditorForModel
” function will automatically generate UI controls looking at the model properties. So we do not need to create control individually as we did for Lab 4.
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%= Html.EditorForModel() %>
<input type="submit" value="Submit customer data" />
<%}%>
Step 3: Enable client validation
As said previously we would like to fire validation on both the server and client side. In order to fire validations on the client side, we need to refer to three JavaScript files as shown in the below code snippet.
<head runat="server">
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>" type="text/javascript"></script>
<% Html.EnableClientValidation(); %>
</head>
Also note the call to the EnableClientValidation
method due to which client side validations are enabled.
<% Html.EnableClientValidation(); %>
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, 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 a Regular Expression, you can use the 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; }
Sometimes you would like to compare the values of a field with another field, we can use the Compare
attribute.
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }
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 object 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
Till now this article was using MVC 2 but it’s high time we also start discussing and doing labs with new release versions of MVC frameworks. Change is a part of human life and the same stands true for MVC as well J. So in this section let’s discuss MVC 3 which is the next release version after MVC 2.
FYI: The recent version is MVC4 and in later days I will touch base even those versions. So have patience.
In case you have not installed this, then click and get MVC 3 template.
In case you are feeling that whatever we have learnt in MVC 2 is a waste, no, not at all. On the contrary MVC 3 is backwards compatible with MVC 2. So whatever you have learnt in MVC 2 still holds true in MVC 3.
Now rather than discussing about all the new features let’s focus on the biggest feature of MVC3 which I personally think is a game changer, and that is Razor.
So what’s Razor? just to answer short and sweet, it’s a type of view for MVC. In MVC 2 the default view was ASP.NET pages, i.e., Web form view. Now, the problem of web form views was that it was not made thinking MVC in mind, so the syntaxes are a bit heavy.
Developers demanded for a clean, lightweight view and with less syntactic noise: The answer is Razor.
So let’s create a simple lab to demonstrate the use of Razor views.
Step 1: Install MVC 3 and create a project using the same
Install MVC 3 templates and create a project selecting the MVC 3 template below.
Step 2: Select Razor
The next screen pops up what kind of application you want to create.
For now let’s keep life simple and let’s select the empty option. The second thing we need to select is what kind of view we want, so let’s 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 a common page which will be used by views for common things like layout and common code.
Step 3: Add a view and invoke the same from the controller
Now go ahead and add a new view and invoke this view from the controller. Adding and invoking the view from the controller remains the same as discussed in the previous labs. Just remember to select the view as the 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, let's run through some common Razor syntaxes and try to get a feel of 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 a 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 an ASPX view, you need to type the below code. So isn’t the syntax much simpler, neat, and lightweight?
<%=DateTime.Now%>
Practice 2: Multiple lines of code
If you have multiples line of code you can use “@
” followed by “{“as shown in the below code snippet.
@{
List<string> obj = new List<string>();
obj.Add("Mumbai");
obj.Add("Pune");
obj.Add("Banglore");
obj.Add("Lucknow");
}
Practice 3: Foreach loop and IF conditions
For loops and if conditions become simpler as shown in the below lines of code.
@foreach (string o in obj)
{
@o <br />
}
@if (DateTime.Now.Year.Equals(2011))
{
// Some code here
}
Practice 4: Do not worry about @
If you are thinking if Razor confuse with @ of Razor and @ of your email address, do not worry, Razor understands the difference. For instance in the below line, the first line Razor will execute as a code and the second line of code it understands is just an email address.
@DateTime.Now
questpond@yahoo.com
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 = "<a href='http://www.questpond.com'>Click here</a>";
}
@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 that’s not what we expect. We were expecting a proper HTML display. This is done by Razor to avoid XSS attacks (I will discuss about that in later sections).
But no worries, the 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 = "<a href='http://www.questpond.com'>Click here</a>";
}
@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.
Note: - In this article we will not be looking in to fundamentals of Windows and Forms authentication. In case you are new to ASP.NET forms authentication you can read this article link http://www.codeproject.com/Articles/98950/ASP-NET-authentication-and-authorization
So let’s try to implement windows authentication in MVC 3 application.
Now, one way to implement Windows authentication is by creating a project using the Intranet Application option. As said previously, the Intranet Application option is enabled to authenticate users from the Windows Active Directory.
For now we will not use that option, let’s use the empty application option and create from scratch so that we can understand better.
Step 1: Enable Windows authentication
One you have created a project the first step is to enable Windows authentication using the <authorization> tag shown below. Yes, this code is the same as we did for ASP.NET.
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Step 2: Just some defects
In MVC 3 template, there is a small defect. It runs forms authentication by default. Set the below tags in the appsettings
tag to avoid problems. It took me two hours to figure this out, what a waste!
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
</appSettings>
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 the roles if you wish.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
publicActionResult 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 it’s time 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 click on the project and select “Add deployable dependencies”.
In the next screen it will prompt which dependencies you want to include. For now I have the Razor view so I have selected both the options.
Once you can see the dependent DLLs been added to the project.
Step 5: Create IIS application
The next step is to create an IIS application with only Windows authentication enabled as shown in the below figure.
Step 6: Publish
Once you have created the IIS application, it’s 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 publish method, you can use your own choice.
Step 7: Run the controller and action
Finally run the controller and action and see how the Windows authentication box pops up for user ID 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 action which invokes a view called as Index. This index view will take inputs like username and password.
public ActionResult Index(){return View();}
Step 2:- Create the index view
The next step is to create the login form which will take username and password. To create the form I have used razor view and the HTML helper classes. In case you are new to HTML helper classes please see Day 1 lab.
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") <br /> Password :- @Html.TextBox("txtPassword") <br /> <input type="submit" value="Login" /> <br /> @{ 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;}<!DOCTYPE html><html><head> <title>About</title></head><body> <div> This is About us </div></body></html>
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 controller’s they will be sent back to the “Index” view i.e. back to 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.
<authentication mode="Forms"> <forms loginUrl="~/Home/Index" timeout="2880"/> </authentication>
Step 6:- See Forms authentication in action
With those above 5 steps you are now completely ready to go. If you now try to 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.
What’s for the fourth day?
In the fourth day we will look into Jquery, Json, Async controllers and difference between Viewdata, Tempdata, Viewbag and Session Variables. You can read day 4 on below link. Click here for the day fourth MVC step by step.
Final note:You can watch my C# and MVC training videos on various, topics like WCF, SilverLight, LINQ, WPF, Design Patterns, Entity Framework, etc. Do not miss my .NET and C# interview questions and answers book.
For technical training related to various topics including ASP.NET, Design Patterns, WCF, MVC, BI, WPF contact SukeshMarla@gmail.com or visit www.sukesh-marla.com
Start with MVC 5
In case you want to start with MVC 5 start with the below video Learn MVC 5 in 2 days.
In case you are going for interviews you can read my 50 Important MVC interview questions with answer article http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and
Are you completely new to MVC?
In case you are completely a fresher I will suggest starting with the below four videos (which are 10 minutes approximately) so that you can learn MVC quickly.
Lab 1: A simple Hello World ASP.NET MVC application
Lab 2: In this lab we will see how we can share data between the controller and the view using view data
Lab 3: In this lab we will create a simple customer model, flourish it with some data, and display it in a view
Lab 4: In this lab we will create a simple customer data entry screen with some validation on the view
For further reading do watch the below interview preparation videos and step by step video series.