86
So, what’s the agenda? As the article name says, learn MVC; so the agenda is simple, we are going to learn ASP.NET MVC in 7 days. The way we will learn MVC in this series of articles is by doing labs, looking at detailed steps of how to achieve those labs, and also looking at demonstrative videos. This article series is divided into 7 days with 35 hands-on labs and every day we will do 5 labs which will help us achieve our goals. So get ready for day 1. For day 1, shown below is our agenda. We will start with an introduction, do a simple Hello World, and finally in the 6 th lab, we will create a simple customer data entry screen using HTML Helper classes. Lab No. Lab description YouTube video demonstration 1 Introduction, Why MVC? NA. 2 A simple Hello World ASP.NET MVC application. http://youtu.be/ KAKxm4eQP24?hd=1 3 In this lab we will see how we can share data between the controller and the view using view data. http://youtu.be/ Fu9v2MIDlTA?hd=1 4 In this lab we will create a simple http://youtu.be/0- UdqWy9lVc?hd=1

Mvc

Embed Size (px)

DESCRIPTION

Microsoft MVC

Citation preview

Page 1: Mvc

So, what’s the agenda?

As the article name says, learn MVC; so the agenda is simple, we are going to learn ASP.NET MVC in 7 days.

The way we will learn MVC in this series of articles is by doing labs, looking at detailed steps of how to achieve those labs, and also looking at demonstrative videos.

This article series is divided into 7 days with 35 hands-on labs and every day we will do 5 labs which will help us achieve our goals.

So get ready for day 1. For day 1, shown below is our agenda. We will start with an introduction, do a simple Hello World, and finally in the 6th lab, we will create a simple customer data entry screen using HTML Helper classes.

Lab No.

Lab description YouTube video demonstration

1 Introduction, Why MVC? NA.

2A simple Hello World ASP.NET MVC application.

http://youtu.be/KAKxm4eQP24?hd=1

3

In this lab we will see how we can share data between the controller and the view using view data.

http://youtu.be/Fu9v2MIDlTA?hd=1

4

In this lab we will create a simple customer model, flourish the same with some data, and display the same in a view.

http://youtu.be/0-UdqWy9lVc?hd=1

5

In this lab we will create a simple customer data entry screen with some validation on the view.

http://youtu.be/1dlxtHuRw34?hd=1

6

This lab will demonstrate how to expedite your MVC development process using HTML Helper classes.

Pending…

Page 2: Mvc

Here you can watch my .NET interview questions and answers videos on various topics like WCF, Silverlight, LINQ, WPF, Design Patterns, Entity Framework, etc.

Other Parts of MVC Step by Step in 7 days

Get Part 2 of the MVC step by step article. Get Part 3 of the MVC step by step article.

So why MVC when ASP.NET code-behind is so good?

I am sure all ASP.NET developers love the code-behind concept. Accepting something new like MVC will not be easy for them. So let’s analyze the problems with the current code-behind concept.

When we generally talk about ASP.NET applications built on a tiered architecture they are divided in four parts: UI (ASPX pages), code-behind (ASPX.CS pages), middle tier (.NET classes), and finally the Data layer.

If you look from the aspect of code distribution, the major code which has logic is in the middle tier or in the code-behind (ASPX.CS files). The UI or ASPX files are HTML files which are more about UI design, and data access logic is pretty much standard components like enterprise data blocks, entity data contexts, etc.

Page 3: Mvc

Let’s try to analyze the problems.

Problem number 1: Unit Testing

From the aspect of unit testing we can exclude the data logic and the UI HTML. The data logic classes are already time tested components like enterprise data block, entity data context, or LINQ data context. So we really do not have to put a lot of effort on testing the DAL separately. In case you have a custom data access layer it will still be easy to test them as they are simple .NET classes.

There is no logic in testing an ASPX HTML as it’s more about look and feel.

The middle tier is again a simple .NET class like data logic so you can easily do unit testing using VSTS or NUNIT.

Now comes the most important one: the code-behind. The code-behind has a lot of action, and testing it is one of the most important things. The only way to invoke these codes is by doing a manual test. From a time perspective this would not be a great choice.

Page 4: Mvc

Even though Microsoft has always boasted about how the ASP.NET code-behind is separate from the UI, in practical sense, it’s very difficult to decouple ASP.NET code-behind and do unit testing on it.

The ASP.NET code-behind is completely tied up with the ASP.NET HttpContext object which makes unit testing very difficult. Just think os how to unit test the below ASP.NET code-behind. How do I create an HttpCcontext object, how do I simulate the sender and EventArgs objects of the button clicks, etc.

FYI: Many developers talk about mock tests, rhino mocks, etc., but still it is cryptic and the complication increases with session variables, view data objects, and ASP.NET UI controls creating further confusion.

Problem 2: The reality of separation of code and UI

As said previously, the ASPX and the ASPX.CS cannot be decoupled in reality, thus reducing reusability. Yes, Microsoft did say first that the code-behind is different from the UI, but then they are probably separate physical files only and one cannot just exist without the other.

For instance let’s say the same button click code when called via HTTP POST should display using displayinvoice.aspx and when called via HTTP GET should display in a tree view. In other words we would like to reuse the code-behind. Just think of how can we do this using the current code-behind.

Page 5: Mvc

Our HERO MVC (Model, View, and Controller)

That’s where MVC comes to rescue. The code-behind is moved to a simple .NET class called Controller. Any user request first comes to the Controller class, the Controller class then invokes the model, and attaches the model to the view for display to the end user.

As this controller class is a simple .NET class we can reuse and also do unit testing easily. So let’s see how we can create MVC application using MVC template provided by visual studio.

Page 6: Mvc

Pre-requisite for MVC

Before we start the day let's ensure that you have all the ingredients to create an MVC application.

Visual Studio 2010 or the free Visual Web Developer 2010 Express. These include the ASP.NET MVC 2 template by default.

Visual Studio 2008 SP1 (any edition) or the free Visual Web Developer 2008 Express with SP1. These do not include ASP.NET MVC 2 by default; you must also download and install ASP.NET MVC 2 from http://www. asp.net / mvc / .

So once you have all your pre-requisites it is time to start the first lab.

Lab 1: Creating a simple Hello World ASP.NET MVC application

In this lab we will create a simple Hello World program using an MVC template. We will create a simple controller, attach the controller to a simple index.aspx page, and view the display on the browser.

Video demonstration for lab 1

In case you want to spend more time with your family rather than reading the complete article you can watch the following 5 minute YouTube video: http://youtu.be/KAKxm4eQP24?hd=1.

Page 7: Mvc

Step 1: Create project

Create a new project by selecting the MVC 2 empty web application template as shown in the below figure.

Once you click OK, you have a readymade structure with the appropriate folders where you can add controllers, models, and views.

Page 8: Mvc

Step 2: Add controller

So let’s go and add a new controller as shown in the below figure.

Once you add the new controller, you should see some kind of code snippet as shown below:

Collapse | Copy Codepublic class Default1Controller : Controller{ // // GET: /Default1/ public ActionResult Index() { return View(); }}

Page 9: Mvc

Step 3: Add view

Now that we have the controller we need to go and add the view. So click on the Index function which is present in the control and click on the Add View menu as shown in the below figure.

The add view pops up a modal box to enter the view name which will be invoked when this controller is called as shown in the figure below. For now, keep the view name same as the controller name and also uncheck the master page check box.

Page 10: Mvc

Once you click on the OK button of the view, you should see a simple ASPX page with the below HTML code snippet. In the below code snippet I have added “This is my first MVC application”.

Collapse | Copy Code<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>Index</title></head><body><div>This is my first MVC application</div></body></html>

Step 4: Run the application

If you do a CTRL + F5 you should see an error as shown in the below figure. This error is obvious because we have not invoked the appropriate controller / action.

If you append the proper controller on the URL you should be able to see the proper view.

Page 11: Mvc

So what’s in the next lab?

Now that we have created a simple MVC Hello World, it’s time to see how we can pass data from the controllers to the views. The first hit comes to the controller which will load your business objects or model and you would like to transfer these objects to the view to display them.

Lab 2: Passing data between controllers and views

The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display purposes. As an ASP.NET developer your choice would be to use session variables, view state, or some other ASP.NET session management object.

The problem with using the ASP.NET session or view state object is the scope. ASP.NET session objects have session scope and view state has page scope. For MVC we would like to see the scope limited to the controller and the view. In other words we would like to maintain data when the hit comes to the controller and reaches the view and after that the scope of the data should expire.

That’s where the new session management technique has been introduced in the ASP.NET MVC framework, i.e., ViewData.

Page 12: Mvc

Video demonstration for lab 2

Below is a simple YouTube video which demonstrates the lab for the view data. In this video we will see how we can share data between the controller and the view using view data. So we will create a simple controller, record the current data in a view data variable, and then display the same in the view using the percentage tag: http://youtu.be/Fu9v2MIDlTA?hd=1.

Step 1: Create project and set view data

So the first step is to create a project and a controller. In the controller, set the viewdata variable as shown in the below code snippet and kick off the view.

Collapse | Copy Codepublic class DisplayTimeController : Controller{ // // GET: /DisplayTime/

public ActionResult Index() { ViewData["CurrentTime"] = DateTime.Now.ToString(); return View(); }}

Step 2: Display view data in the view

The next thing is to display data in the view by using the percentage tag. One important point to note is, the view does not have a code-behind. So to display the view we need to use the <%: tag in the ASPX page as shown in the below code snippet.

Collapse | Copy Code<body><div><%: ViewData["CurrentTime"] %></div></body>

Page 13: Mvc

So what’s in the next lab?

So now that we know how to pass data using view data, the next lab is to create a simple model and see all the three MVC entities (i.e., model, view, and controller) in action.

Lab 3: Creating a simple model using MVC

In this lab we will create a simple customer model, flourish it with some data, and display it in a view.

Video demonstration for Lab 3

Below is a video demonstration: http://youtu.be/0-UdqWy9lVc?hd=1.

Step 1: Create a simple class file

The first step is to create a simple customer model which is nothing but a class with three properties: code, name, and amount. Create a simple MVC project, right click on the model folder, and click on Add New Item, as shown in the below figure.

From the templates, select a simple class and name it as Customer.

Page 14: Mvc

Create the class with three properties as shown in the below code snippet.

Collapse | Copy Codepublic class Customer{ private string _Code; private string _Name; private double _Amount;

public string Code { set { _Code = value; } get { return _Code; } }

public string Name { get { return _Name; } set { _Name = value; } }

public double Amount { set { _Amount = value; } get { return _Amount; } }}

Page 15: Mvc

Step 2: Define the controller with action

The next step is to add the controller and create a simple action display customer as shown in the below code snippet. Import the model namespace in the controller class. In the action, we create an object of the customer class, flourish with some data, and pass it to a view named “DisplayCustomer”.

Collapse | Copy Codepublic class CustomerController : Controller{ ….. …. public ViewResult DisplayCustomer() { Customer objCustomer = new Customer(); objCustomer.Id = 12; objCustomer.CustomerCode = "1001"; objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer); }}

Step 3: Create strongly typed view using the class

We need to now join the points of MVC by creating views. So right click on the view folder and click Add View. You should see a dropdown as shown in the below figure. Give a view name, check Create a strongly typed view, and bind this view to the

Page 16: Mvc

customer class using the dropdown as shown in the below figure.

The advantage of creating a strong typed view is you can now get the properties of the class in the view by typing the model and “.” as shown in the below figure.

Page 17: Mvc

Below is the view code which displays the customer property value. We have also put an if condition which displays the customer as a privileged customer if above 100 and a normal customer if below 100.

Collapse | Copy Code<body><div>The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>This is a priveleged customer<% } else{ %>This is a normal customer<%} %>

</div></body>

Step 4: Run your application

Now the “D” thing, hit Ctrl + F5 and pat yourself for one more lab success.

So what’s in the next lab?

In this sample we flourished the customer object from within the controller. In the next lab we will take data from an input view and display it. In other words we will see how to create data entry screens for accepting data from views.

Page 18: Mvc

Lab 4: Creating a simple MVC data entry screen

Every project small or big needs data entry screens. In this lab we will create a simple customer data entry screen as shown in the below figure using an MVC template.

As soon as the end user enters details and submits data it redirects to a screen as shown below. If the entered amount is less than 100 it displays normal customer, else it displays privileged customer.

Video demonstration for lab 4

Here is a simple video demonstration for this lab: http://youtu.be/1dlxtHuRw34?hd=1.

Page 19: Mvc

Step 1: Creating your data entry ASPX page

The first step is to create the data entry page using the simple HTML form action tag as shown in the below code snippet. The most important point to note in the below code snippet is that the action is pointing to the controller action, i.e., ‘DisplayCustomer’.

Collapse | Copy Code<form action="DisplayCustomer" method="post">Enter customer id :- <input type="text" name="Id" /> <br />Enter customer code :- <input type="text" name="CustomerCode" /><br />Enter customer Amount :-<input type="text" name="Amount" /><br /><input type="submit" value="Submit customer data" /></form>

Step 2: Creating the controller

The above defined form action will post to the controller class and on the function “DisplayCustomer”. So we need to get the data from the HTML controls, flourish the object, and send the object to the view.

Below is the code snippet of DisplayCustomer which flourishes the customer object by collecting data from Request.Form and sends the object to the view DisplayCustomer.

Collapse | Copy Codepublic class CustomerController : Controller{ ….. …. [HttpPost] public ViewResult DisplayCustomer() { Customer objCustomer = new Customer(); objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString()); objCustomer.CustomerCode = Request.Form["Id"].ToString(); objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ; return View("DisplayCustomer", objCustomer); }}

Step 3: Create the view to display the customer object

The next step is to create the “DisplayCustomer” view. So right click on the view folder and click Add view. You should see a dropdown as shown in the below figure. Give a view name, check Create a strongly typed view, and bind this view to the customer class using the dropdown, as shown in the below figure.

Page 20: Mvc

The advantage of creating a strong typed view is you can now get the properties of the class in the view by typing the model and “.” as shown in the below figure.

Below is the view code which displays the customer property value. We have also put an if condition which displays the customer as a privileged customer if above 100 and normal customer if below 100.

Page 21: Mvc

Collapse | Copy Code<body><div>The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>This is a priveleged customer<% } else{ %>This is a normal customer<%} %>

</div></body>

Step 4: Finally run the project

The final step is to run the project and see the output.

You should also be able to test above 100 and below 100 scenarios.

Page 22: Mvc

So what’s in the next lab?

In this lab we created a simple data entry screen which helped us flourish the customer object. This customer object was then passed to the view for display. If you closely watch the current lab we have done a lot of coding, i.e., creating the HTML screens, flourishing the object, etc. It would be great if there was some kind of automation. In the next lab we see how HTML helper classes help to minimize many of these manual coding and thus increase productivity.

Lab 5: Using HTMLHelper to create views faster

In our previous lab we created a simple customer data entry screen. We completed the lab successfully but with two big problems:

The complete HTML code was written manually. In other words, it was less productive. It’s like going back to the dark ages where developers used to write HTML tags in Notepad.

Collapse | Copy Code<form action="DisplayCustomer" method="post">Enter customer id :- <input type="text" name="Id" /> <br />Enter customer code :- <input type="text" name="CustomerCode" /><br />Enter customer Amount :-<input type="text" name="Amount" /><br /><input type="submit" value="Submit customer data" /></form>

Page 23: Mvc

Added to that, a lot of manual code was also written in the controller to flourish the object and send data to the MVC view.

Collapse | Copy Codepublic class CustomerController : Controller{ ….. …. [HttpPost] public ViewResult DisplayCustomer() { Customer objCustomer = new Customer(); objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString()); objCustomer.CustomerCode = Request.Form["Id"].ToString(); objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ; return View("DisplayCustomer", objCustomer); }}

In this lab we will see how to use MVC HTMLHelper classes to minimize manual coding and increase productivity.

Step 1: Create the Customer class

Create a simple customer class, please refer to Lab 5 for details.

Step 2: Creating the input HTML form using helper classes

HTML helper classes have readymade functions by which you can create HTML controls with ease. Go to any MVC view and see the intellisense for the HTMLHelper class, and you should see something as shown in the below figure.

By using the HTMLHelper class you can create any HTML control like TextBox, Label, ListBox, etc., just by invoking the appropriate function.

Page 24: Mvc

In order to create the form tag for HTML we need to use “Html.BeginForm”. Shown below is the code snippet for that:

Collapse | Copy Code<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post)) {%>-- HTML input fields will go here <%} %>

The above code will generate the below HTML:

Collapse | Copy Code<form action="DisplayCustomer" method="post">…..…..</form>

The HTML helper “beginform” takes three input parameters: action name (method inside the controller), controller name (actual controller name), and HTTP posting methodology (POST or GET).

If you want to create a text box, simply use the “TextBox” function of the HTMLHelper class as shown in the below code. This way you can create HTML controls using the HTMLHelper class functions.

Collapse | Copy CodeEnter customer id :- <%= Html.TextBox("Id",Model)%> <br />

The above code snippet will generate the below HTML code:

Collapse | Copy CodeEnter customer id :- <input type="text" name="Id" /> <br />

To create a data entry screen like the one shown below, we need to the use the below code snippet.

Page 25: Mvc

Collapse | Copy Code<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post)){ %>Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />Enter customer code :- <%= Html.TextBox("CustomerCode",Model) %><br />Enter customer Amount :- <%= Html.TextBox("Amount",Model) %><br /><input type="submit" value="Submit customer data" /><%} %>

Step 3: Create a strong typed view by using the customer class

So once you have created the view using the HTMLHelper classes it’s time to attach the customer class with the view; please refer to lab 5 for details.

Step 4: Creating the controller class

The final thing is the controller code. The controller code now becomes very simple. The customer object will be auto flourished as we have used the HTML Helper classes. You will create the controller class as we did in Lab 4 but we do not need to write any kind of code for connecting the HTML screens with the controller, it’s all hidden and automated.

Collapse | Copy Code[HttpPost]public ActionResult DisplayCustomer(Customer obj){ return View(obj);}

Enjoy your output for different conditions of customer amounts entered.

Page 26: Mvc

So, what’s the agenda?

This article is continuation to Learn MVC step by step in 7 days you can read the first day from  Click here for Day 1 article .

Get Part 3 of the MVC Step by Step article.

In day 2 we will look in do the following 4 labs.

• Writing unit tests on MVC projects.• Configure MVC routings.• Validating MVC routes.• Configure MVC outbound routes.

In case you are completely a fresher I will suggest to start with the below 4 videos which are 10 minutes approximately so that you can come to MVC quickly. 

Lab No. Lab description

Youtube Video demonstration for the same

1A simple Hello world ASP.NET MVC application.

http://youtu.be/KAKxm4eQP24?hd=1

2In this Lab we will see how we can share data between controller and the view using view data.

http://youtu.be/Fu9v2MIDlTA?hd=1

3

In this lab we will create a simple customer model, flourish the same with some data and display the same in a view.

http://youtu.be/0-UdqWy9lVc?hd=1 

4In this lab we will create a simple customer data entry screen with some validation on the view.

http://youtu.be/1dlxtHuRw34?hd=1 

So let’s start with the above 4 labs one by one.

Page 27: Mvc

Lab 6:- Unit test MVC projects

When we started this whole MVC series (Day 1) we started with two concerns regarding behind code:-

• How can we do unit testing on the ASP.NET behind code?• How can we reuse the ASP.NET behind code with different user interfaces?

In this section let’s concentrate on the first point i.e. Unit testing.

Just a quick recap if we need to unit test the below method “btngenerateinvoices_click” in ASP.NET behind code , we have the following problems :-

• How do we create the sender and eventargs object?• The below complete code runs under HttpContext object, how do I mimic them?• What about ASP.NET UI controls , how do I access them ?• What about other ASP.NET object like session object, application, how do I access them?.

FYI: - Many developers would talk about mock test, rhino mocks etc but still its cryptic and the complication increases with session variables, view data objects, ASP.NET UI controls creating further confusion.

So what we will do in this section is we will create a simple MVC application and we will do unit test on the ASP.NET application using VSTS unit test framework.

Page 28: Mvc

Step1:- Create the simple display customer screen project

The first step is to create a simple MVC project. We will use the same project which we have discussed in MVC (Model view controller) day 1 LearnMVC.aspx.  So in case you do not have any sample project please create one using the link above.

The controller class at the end of the day is a simple .NET class. For instance if you watch your project code closely, you can easily see the customer controller class as shown below.

Collapse | Copy Codepublic class CustomerController : Controller{.......public ViewResult DisplayCustomer(){Customer objCustomer = new Customer();objCustomer.Id = 12;objCustomer.CustomerCode = "1001";objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);}}

In simple words because this is a simple .NET class we can easily instantiate the class and create automated unit tests for the same. That’s what exactly we are going to do in our next steps.

Step 2:- Add a simple unit test project

Let’s use our VSTS unit test framework to test the controller class. In case you are a complete fresher to VSTS unit testing we would request to see this article to get a hang of unit testing http://www.codeproject.com/KB/cs/VSTSTesting.aspx  . Add a new project

Page 29: Mvc

to your solution using the test project solution template.

Step 3:- Add appropriate project references

We need to add reference to the MVC application in our unit test project so that we can get hold of the controller class.

Page 30: Mvc

Once you add the references you should see the MVC application in your project references as shown in the below figure.

Step 4:- Write the unit test

Once you have added the references open the unit test class i.e. ‘UnitTest1.cs’. In this class create a simple test method called as ‘DisplayCustomer’ which is attributed by ‘TestMethod’ attribute as shown in the below code snippet.

If you see the below code snippet we are creating object of the controller class, invoking the controller action i.e. ‘DisplayCustomer’ and then checking if the view name is ‘DisplayCustomer’. If they are equal that means the test passes or else it fails.

Collapse | Copy Code[TestMethod]public void DisplayCustomer(){CustomerController obj = new CustomerController();var varresult = obj.DisplayCustomer();Assert.AreEqual("DisplayCustomer", varresult.ViewName);}

Page 31: Mvc

Step 5 :- Finally run the unit test

Once you have written your test case it’s time to run the test case by clicking on test , windows and then clicking test view.

Page 32: Mvc

On the test view right click on the test and run the selected test case as shown below.

Page 33: Mvc

If everything goes well you should see green color indicating that the test has passed or else you should see a red color with details regarding why the test failed.

So what’s in the next Lab

In the next lab we will discuss about MVC routing. MVC is all about connecting the actions to the controllers and MVC routing helps us to achieve the same. So be ready to get routed in our next tutorial.

Lab 7:- Understanding MVC routing

Page 34: Mvc

Introduction

At the end of the day MVC is nothing but URL mapped to controllers and controllers mapped to actions.

For example when a user sends a request URL like www.questpond.com/locateproduct  from the browser, these actions are mapped with MVC controllers and MVC controllers finally invokes those functions.

Below is a simple table which shows how the whole thing looks like.

Page 35: Mvc

Adding further to the complication we can have multiple URL’s mapped to one controller or you can have more than one controller mapped to a single URL. For instance you can have www.questpond.com/contactus  and www.questpond.com/aboutus  mapped to a single controller called as “AboutUsController”.

Page 36: Mvc

It would be great if we have some kind of mechanism by which we can configure these mappings. That’s what exactly MVC routing is meant for. MVC routing helps to easily configure and map the URL with the controllers.

Step 1:- Take the MVC project created in Day 1.

Let’s take the same customer project we had discussed in the previous section.

Step 2 :- Change global.asax.cs

All route mappings are stored in the “global.asax.cs” behind code file. So the first step is we need to go and change this file.

Page 37: Mvc

All routing mapping are stored in to a collection called as ‘routes’. This collection belongs to the namespace “System.Web.Routing”. To add a route you need to call the ‘MapRoute’ method and pass three parameters “name”,”url” and “defaults”.

Below is a print screen of the snippet of the ‘maproute’ function.

“Name” is the key name by which the route will be identified from the collection.

“Url” defines what kind of URL format we want to connect with the controllers. For instance in the below code snippet we are saying that “View/ViewCustomer” is the URL format.

“Defaults” defines the controller class and action functions which will be invoked when the URL is called. For instance in the below code we are saying that when “View/ViewCustomer” is called it will invoke the “Customer” controller class and the action function invoked will be “DisplayCustomer”.

In case your controller takes parameters you can use the “{“brackets. For instance in the below code snippet we have used “{“to specify that we can have “id” parameter.

If you want to define the parameter as optional you can use the “UrlParameter.Optional” enum.

Page 38: Mvc

The first thing is comment the default mapping code. We will explain the default mapping code later.

Collapse | Copy Code//routes.MapRoute(// "Default", // Route name// "{controller}/{action}/{id}", // URL with parameters// new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults

Put the below code , which means when we call http://localhost/View/ViewCustomer/  it will invoke the customer controller and will call displaycustomer function.

Collapse | Copy Coderoutes.MapRoute("View", // Route name"View/ViewCustomer/{id}", // URL with parametersnew { controller = "Customer", action = "DisplayCustomer", id = UrlParameter.Optional }); // Parameter defaults

Below is the action function “DisplayCustomer” which will be invoked.

Collapse | Copy Codepublic ViewResult DisplayCustomer(){Customer objCustomer = new Customer();objCustomer.Id = 12;objCustomer.CustomerCode = "1001";objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);}

Step 3:- Run the application

If you run the application you should see the below display.

Page 39: Mvc

If you remember we commented the default entry route. Let’s understand what exactly this default code meant.

"{controller}/{action}/{id}" defines that URL will be automatically named with the convention of controller name / function action name / value. So if you have a controller class with ‘Customer” and action function as “Search” then the URL will be structured as http://xyz.com/Customer/Search  automatically.

Collapse | Copy Code//routes.MapRoute(// "Default", // Route name// "{controller}/{action}/{id}", // URL with parameters// new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults

So what’s in the next Lab

In the next lab we will discuss how to validate MVC URL. All actions to MVC come via MVC URL and even data is fed via MVC URL. So in the next section we will see how we can validate the data passed in the MVC URL.

Lab 8:- Validating and setting default values to MVC URLS

MVC is all about action which happens via URL and data for those actions is also provided by the URL. It would be great if we can validate data which is passed via these MVC URL’s.

For instance let’s consider the MVC URL http://localhost/Customer/ViewCustomer  . If anyone wants to view customer details for 1001 customer code he needs to enter http://localhost/Customer/ViewCustomer/1001 .

The customer code is numeric in nature. In other words anyone entering a MVC URL

Page 40: Mvc

like http://localhost/Customer/ViewCustomer/Shiv  is invalid. MVC framework provides a validation mechanism by which we can check on the URL itself if the data is appropriate. In this lab we will see how to validate data which is entered on the MVC URL.

Step 1:- Create a simple customer model

The first is to create a simple customer class model which will be invoked by the controller.

Collapse | Copy Codepublic class Customer{public int Id { set; get; }public string CustomerCode { set; get; }public double Amount { set; get; }}

Step 2:- Create the controller class

The next step is to create a simple controller class which has collection of the customer model object which was created in step 1.

Collapse | Copy Codepublic class CustomerController : Controller{List<Customer> Customers = new List<Customer>();//// GET: /Customer/public CustomerController(){Customer obj1 = new Customer();obj1.Id = 12;obj1.CustomerCode = "1001";obj1.Amount = 90.34;

Customers.Add(obj1);

obj1 = new Customer();obj1.Id = 11;obj1.CustomerCode = "1002";obj1.Amount = 91;Customers.Add(obj1);

}

[HttpGet]public ViewResult DisplayCustomer(int id){Customer objCustomer = Customers[id];

return View("DisplayCustomer",objCustomer);

Page 41: Mvc

}}

The controller has a simple ‘DisplayCustomer’ function which displays the customer using the ‘id’ value. This function takes the ‘id’ value and looks up through the customer collection. Below is the downsized reposted code of the function.

Collapse | Copy Code[HttpGet]public ViewResult DisplayCustomer(int id){Customer objCustomer = Customers[id];

return View("DisplayCustomer",objCustomer);}

If you look at the ‘DisplayCustomer’ function it takes an ‘id’ value which is numeric. We would like put a validation on this id field with the following constraints:-

• Id should always be numeric.• It should be between 0 to 99.

We want the above validations to fire when the MVC URL is invoked with data.

Step 3:- Apply validation using regex on the MVC routes

The validation described in the step 2 can be achieved by applying regular expression on the route map. If you go to global.asax file and see the maproute function on the inputs to this function is the constraint as shown in the below figure.

In case you are new to regular expression we would advise you to go through this video on regular expressions http://youtu.be/C2zm0roE-Uc?hd=1

So in order to accommodate the numeric validation we need to the specify the regex constraint i.e. ‘\d{1,2}’ in the ‘maproute’ function as shown below. ‘\d{1,2}’ in regex means that the input should be numeric and should be maximum of length 1 or 2 , i.e. between 0 to 99.

Page 42: Mvc

You can specify default values by saying id=0 as shown in the below code snippet. So just in case if some one does not specify the value to the id it will take the value as zero by default.

Collapse | Copy Coderoutes.MapRoute("View", // Route name"View/ViewCustomer/{id}", // URL with parametersnew { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id = @"\d{1,2}" }); // Parameter defaults

Step 4:- Test if it works

So now that we are done with the validation using the ‘maproute’ functions, it’s time to test if these validations work.

So in the first test we have specified valid 1 and we see that the controller is hit and the data is displayed.

If you try to specify value more than 100 you would get error as shown below. Please note that the error is confusing but it’s the effect of the regex validation which is specified on the maproute function.

Page 43: Mvc

If you try to specify a non-numeric value you should again get the same error which confirms that our regex validation is working properly.

The most important point to note is that these validations are executed even before the request reaches the controller functions.

So what’s in the next lab

One of the crucial things in any website development is defining navigations from one page to the other page. In MVC everything is an action and those actions invoke the views or pages. We can not specify direct hyperlinks like www.questpond.com/home.aspx  , this would defeat the purpose of MVC. In other words we need to specify actions and these actions will invoke the URL’s.

Page 44: Mvc

In the next lab we will look in to how to define outbound URL in MVC views which will help us to navigate from one page to other page.

Lab 9:- Understanding MVC outbound URLs

Introduction

When we talk about web applications end users would like to navigate from one page to other page. So as a simple developer your first thought would be to just give page names as shown in the below figure.

So for example if you want to go and browse from home.aspx to about.aspx give the anchor hyper link page name and things should be fine.

By doing that you are violating MVC principles. MVC principle says that hit should first come to the controller but by specifying <a href=”Home.aspx”> the first hit comes to the view. This bypasses your controller logic completely and your MVC architecture falls flat.

Page 45: Mvc

Ideally the actions should direct which page should be invoked. So the hyperlink should have actions in the anchor tags and not the page names i.e. direct view name.

Step 1:- Create views

Lets create three views as shown in the below figure “Home”,”About” and “Product”.

Let’s create a simple navigation between these 3 pages as shown below. From the home view we would like to navigate to about and product view. From about and product view we would like to navigate back to the home view.

Page 46: Mvc

Step 2 :- Create controller for the views

Next step is to define controller actions which will invoke these views. In the below code snippet we have defined 3 actions “GotoHome” (this invokes home view), “Aboutus” ( this invokes the about view) and “SeeProduct” ( this invokes product view).

Collapse | Copy Codepublic class SiteController : Controller{//// GET: /Site/

public ActionResult GotoHome(){return View("Home");}

public ActionResult AboutUs(){return View("About");}

public ActionResult SeeProduct(){return View("Product");}}

Step 3:- Provide actions in the link

To invoke the actions rather than the views we need to specify the actions in the anchor tag as shown in the below code snippet.

Collapse | Copy CodeThis is products<a href="GotoHome">Go Home</a><br /><a href="Aboutus">About us</a><br />

If you want to create the anchor links using the HTML helper classes you can use the action link function as shown in the below code snippet.

Collapse | Copy Code<%= Html.ActionLink("Home","Gotohome") %>

The above code was for the products page , you can do the same type of navigations for the about us and the home page.

Collapse | Copy CodeThis is About us<a href="GotoHome">Go Home</a><br />

Page 47: Mvc

<a href="SeeProduct">See Product</a><br />

This is home page<br /><a href="SeeProduct">See Product</a><br /><a href="Aboutus">About us</a><br />

Collapse | Copy Code</div>

Step 4:- Enjoy your navigation

Once you have specified the actions inside the link you navigate between home, about and products page.

Page 48: Mvc

While navigating you can see how the URL’s are pointing to the actions rather than absolute page names like home.aspx, aboutus.aspx etc which violates the complete MVC principle.

Page 49: Mvc

So, what’s the agenda?

In day 3 of Learn MVC Step by step we will look in do the following below 5 labs.  In case you want to see the Day 1 and Day 2 articles you can start from Learn MVC ASP.NET step by step .

Partial views. Validations using data annotations. Razor (MVC 3). MVC Windows authentication MVC Forms Authentication

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.

Day 1: Controllers, strong typed views, and helper classes

If you are new to the series or want to refresh what we covered in  Day 1 then click and go to read it.

Day 2: Unit test, routing,  and outbound URLs

See here what we did in Day 2 of MVC so that we can get in synch.

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”.

Page 50: Mvc

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.

Page 51: Mvc

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.

Collapse | Copy Code<%@ 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.

Collapse | Copy Code<body><div><% Html.RenderPartial("MyView"); %></div> </body>

Page 52: Mvc

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.

Page 53: Mvc

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.

Collapse | Copy Codeusing 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.

Collapse | Copy Codepublic 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.

Collapse | Copy Code<%= 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.

Page 54: Mvc

Collapse | Copy Code<% 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.

Collapse | Copy Code<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.

Collapse | Copy Code<% 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.

Collapse | Copy Code[HttpPost]public ActionResult PostCustomer(Customer obj){if (ModelState.IsValid){ obj.Save(); return View("Thanks");}else{ return View("Customer");}

Page 55: Mvc

}

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.

Collapse | Copy Code[StringLength(160)]public string FirstName { get; set; }

In case you want to use a Regular Expression, you can use the RegularExpression attribute.

Collapse | Copy Code[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.

Collapse | Copy Code[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.

Collapse | Copy Codepublic 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.

Page 56: Mvc

Collapse | Copy Codevar 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.

Collapse | Copy CodeTryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use “AddModelError” function.

Collapse | Copy CodeModelState.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 .  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

Page 57: Mvc

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.

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.

Page 58: Mvc

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.

Page 59: Mvc

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.

Page 60: Mvc

Collapse | Copy Code

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.

Collapse | Copy CodeTodays 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?

Collapse | Copy Code<%=DateTime.Now%>

Page 61: Mvc

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.

Collapse | Copy Code@{ 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.

Collapse | Copy Code@foreach (string o in obj){ @o <br />}

Page 62: Mvc

Collapse | Copy Code@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.

Collapse | Copy [email protected]@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.

Collapse | Copy CodeTweet 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.

Collapse | Copy Code@{ 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).

Page 63: Mvc

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.

Collapse | Copy Code@{ 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.

Page 64: Mvc

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 tag shown below.  Yes, this code is the same as we did for ASP.NET.

Collapse | Copy Code<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!

Collapse | Copy Code<add key="autoFormsAuthentication" value="false" /><add key="enableSimpleMembership" value="false"/>

Collapse | Copy Code<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>

Page 65: Mvc

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.

Collapse | Copy Code[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”.

Page 66: Mvc

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.

Page 67: Mvc

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.

Page 68: Mvc

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.

Page 69: Mvc

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.

Collapse | Copy Codepublic 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.

Collapse | Copy Code @{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(); }

Page 70: Mvc

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.

Collapse | Copy Codeif ((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.

Collapse | Copy Codepublic 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. 

Collapse | Copy Code@{ 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. 

Collapse | Copy Code[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.

Page 71: Mvc

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.

Collapse | Copy Code <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.