learn mvc.docx

105
Learn MVC (Model View Controlle r) Learn MVC (Model View Controller) step by step in 7days – Day 1 [1] Contents So, what’s the agenda? Other parts of MVC step by step in 7 days So why MVC when ASP.NET code-behind is so good? Problem number 1: Unit testing Problem 2: The reality of separation of code and UI Our HERO MVC (Model , view and controller) Pre-requisite for MVC Lab 1: Creating a simple Hello World ASP.NET MVC application o Video demonstration for Lab 1 o Step 1: Create project o Step 2: Add controller o Step 3: Add view o Step 4: Run the application o So what’s in the next lab? Lab 2: Passing data between controllers and view s o Video demonstration for Lab 2 o Step 1: Create project and set view data o Step 2: Display view data in the view o So what’s in the next lab? Lab 3: Creating a simple model using MVC o Video demonstration for Lab 3 o Step 1: Create a simple class file o Step 2: Define the controller with action o Step 3: Create strongly typed view using the class o Step 4: Run your application o So what’s in the next lab? Lab 4: Creating a simple MVC data entry screen o Video demonstration for Lab 4 o Step 1: Creating your data entry ASPX page o Step 2: Creating the controller o Step 3: Create the view to display the customer object

Upload: asadhppy

Post on 01-Jan-2016

146 views

Category:

Documents


3 download

DESCRIPTION

Learn MVC

TRANSCRIPT

Page 1: Learn MVC.docx

Learn MVC (Model View Controller)

Learn MVC (Model View Controller) step by step in 7days – Day 1 [1]

Contents So, what’s the agenda? Other parts of   MVC   step   by   step   in 7   days So why   MVC   when ASP.NET code-behind is so good? Problem number 1: Unit testing Problem 2: The reality of separation of code and UI Our HERO   MVC   (Model ,   view   and   controller) Pre-requisite for   MVC Lab 1: Creating a simple Hello World ASP.NET   MVC   application o Video demonstration for Lab 1  o Step   1: Create project o Step   2: Add controller o Step   3: Add   view  o Step   4: Run the application  o So what’s in the next lab?   Lab 2: Passing data between controllers and   view s o Video demonstration for Lab 2 o Step   1: Create project and set   view   data o Step   2: Display   view   data in the   view o So what’s in the next lab? Lab 3: Creating a simple model using   MVC o Video demonstration for Lab 3 o Step   1: Create a simple class file o Step   2: Define the controller with action o Step   3: Create strongly typed   view   using the class o Step   4: Run your application o So what’s in the next lab? Lab 4: Creating a simple   MVC   data entry screen o Video demonstration for Lab 4 o Step   1: Creating your data entry ASPX page o Step   2: Creating the controller o Step   3: Create the   view   to display the customer object o Step   4: Finally run the project o So what’s in the next lab? Lab 5: Using HTML Helper to create   view s faster o Step   1: Create the Customer class o Step   2: Creating the input HTML form using helper classes  o Step   3: Create a strongly typed   view   by using the customer class o Step   4: Creating the controller class

Page 2: Learn MVC.docx

What’s for the second day? 50   MVC   Inter view   questions with answers

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 descriptionYouTube video demonstration

1 Introduction, Why MVC? NA.

2A simple Hello World ASP.NET MVC application.

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

3In 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

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

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

6This lab will demonstrate how to expedite your MVCdevelopment process using HTML Helper classes.

Pending…

Here you can watch my  .NET inter view   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.

Page 3: Learn MVC.docx

Get Part 3 of the MVC step by step article. Get part 4 of 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.

Let’s try to analyze the problems.

Problem number 1: Unit TestingFrom 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.

Page 4: Learn MVC.docx

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.

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 UIAs 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.aspxand 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: Learn MVC.docx

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 theview 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 createMVC application using MVC template provided by visual studio.

Pre-requisite for MVCBefore 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 fromhttp://www.asp.net/ mvc / .

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

Page 6: Learn MVC.docx

Lab 1: Creating a simple Hello World ASP.NET MVCapplicationIn 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 1In 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.Step 1: Create projectCreate 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.

Step 2: Add controller

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

Page 7: Learn MVC.docx

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

 Collapse | Copy Code

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

Step 3: Add viewNow 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 8: Learn MVC.docx

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.

Page 9: Learn MVC.docx

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

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 theviews. 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 viewsThe 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.

Page 10: Learn MVC.docx

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

Video demonstration for lab 2Below 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 dataSo 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 Code

public class DisplayTimeController : Controller{ // // GET: /DisplayTime/

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

Step 2: Display view data in the viewThe next thing is to display data in the view by using the percentage tag. One important point to note is, the viewdoes 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>

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 threeMVC entities (i.e., model, view, and controller) in action.

Lab 3: Creating a simple model using MVCIn this lab we will create a simple customer model, flourish it with some data, and display it in a view.Video demonstration for Lab 3Below is a video demonstration: http://youtu.be/0-UdqWy9lVc?hd=1.

Page 11: Learn MVC.docx

Step 1: Create a simple class fileThe 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.

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

 Collapse | Copy Code

public class Customer{ private string _Code; private string _Name; private double _Amount;

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

public string Name {

Page 12: Learn MVC.docx

get { return _Name; } set { _Name = value; } }

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

Step 2: Define the controller with actionThe 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 Code

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

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

Step 3: Create strongly typed view using the classWe 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 customer class using the dropdown as shown in the below figure.

Note :- In case you are not able to see the model in the drop down , please compile your project once.  

Page 13: Learn MVC.docx

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 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 />

Page 14: Learn MVC.docx

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

Lab 4: Creating a simple MVC data entry screenEvery 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.

Page 15: Learn MVC.docx

Video demonstration for lab 4Here is a simple video demonstration for this lab: http://youtu.be/1dlxtHuRw34?hd=1.Step 1: Creating your data entry ASPX pageThe 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 controllerThe 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 fromRequest.Form and sends the object to the view DisplayCustomer.

 Collapse | Copy Code

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

Page 16: Learn MVC.docx

Step 3: Create the view to display the customer objectThe 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.

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 17: Learn MVC.docx

 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 projectThe final step is to run the project and see the output.

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

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

Page 18: Learn MVC.docx

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 fasterIn 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>

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

 Collapse | Copy Code

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

In this lab we will see how to use MVC 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 classesHTML helper classes have readymade functions by which you can create HTML controls with ease. Go to any MVCview and see the intellisense for the HTMLHelper class, and you should see something as shown in the below figure.

Page 19: Learn MVC.docx

By using the HTMLHelper class you can create any HTML control like TextBox, Label, ListBox, etc., just by invoking the appropriate function.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 Code

Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />

The above code snippet will generate the below HTML code:

 Collapse | Copy Code

Enter 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 20: Learn MVC.docx

 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 classSo 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 21: Learn MVC.docx

So have a toast of beer for completing your first day of MVC labs.

What’s for the second day? In the second session, we will talk about URL routing, ease of MVC unit testing, MVC Controller attributes, and a lot more. The next lab will be a bit more advanced as compared to the first day. Below is the link for the second day: Click here for the day second   MVC   step   by   step . 

Page 22: Learn MVC.docx

Learn MVC (Model view controller) Step by Step in 7 days – Day 2 [2]

Contents So, what’s the agenda? Lab 6: Unit test MVC projects o Step1: Create the simple display customer screen project o Step 2: Add a simple unit test project o Step 3: Add appropriate project references o Step 4: Write the unit test o Step 5:   Finally run the unit test o So what’s in the next lab? Lab 7: Understanding MVC routing o Introduction o Step 1: Take the MVC project created in Day 1 o Step 2: Change global.asax.cs o Step 3:- Run the application o So what’s in the next lab? Lab 8: Validating and setting default values to MVC URLS o Step 1: Create a simple customer model o Step 2: Create the controller class o Step 3: Apply validation using regex on the MVC routes o Step 4:- Test if it works o So what’s in the next lab? Lab 9: Understanding MVC outbound URLs o Introduction o Step 1: Create views o Step 2: Create controller for the views o Step 3: Provide actions in the link o Step 4: Enjoy your navigation What’s for the third day? 50 MVC Interview questions with answers

So, what’s the agenda?This article is continuation to Learn MVC step by step in 7 days you can read from below links.

Get Part 1 of the MVC Step by Step article. Get Part 3 of the MVC Step by Step article. Get Part 4   of MVC Step by Step article.

In day 2 we will look into the following four labs:

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

Page 23: Learn MVC.docx

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

1 A 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

3In 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.

Lab 6: Unit test MVC projectsWhen 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 objects? The below complete code runs under the HttpContext object, how do I mimic it? What about ASP.NET UI controls, how do I access them? What about other ASP.NET objects like session object, application, how do I access them?

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

Page 24: Learn MVC.docx

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

Step 1: Create the simple display customer screen projectThe 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 projects, 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 Code

public class CustomerController : Controller{.......public ViewResult DisplayCustomer(){Customer objCustomer = new Customer();

Page 25: Learn MVC.docx

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 is exactly what we are going to do in our next steps.

Step 2: Add a simple unit test projectLet’s use our VSTS unit test framework to test the controller class. In case you are a complete fresher to VSTS unit testing, see this article to get a hang of unit testing: http://www.codeproject.com/KB/cs/VSTSTesting.aspx. Add a new project to your solution using the test project solution template.

Step 3: Add appropriate project references

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

Page 26: Learn MVC.docx

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 testOnce you have added the references, open the unit test class, i.e., UnitTest1.cs. In this class create a simple test method called DisplayCustomer which is attributed by the TestMethod attribute as shown in the below code snippet.If you see the below code snippet we are creating an 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()

Page 27: Learn MVC.docx

{CustomerController obj = new CustomerController();var varresult = obj.DisplayCustomer();Assert.AreEqual("DisplayCustomer", varresult.ViewName);}

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 28: Learn MVC.docx

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

If everything goes well you should see a 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 achieve this. So be ready to get routed in our next tutorial.

Page 29: Learn MVC.docx

Lab 7: Understanding MVC routingIntroduction

At the end of the day, MVC is nothing but a 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 30: Learn MVC.docx

Adding further to the complication we can have multiple URLs 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 andwww.questpond.com/aboutus mapped to a single controller called AboutUsController.

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.

Page 31: Learn MVC.docx

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.csAll route mappings are stored in the “global.asax.cs” code-behind file. So the first step is we need to go and change this file.

All routing mappings are stored into a collection called routes. This collection belongs to the namespaceSystem.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 Customercontroller class and the action function invoked will be DisplayCustomer.

Page 32: Learn MVC.docx

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 an id parameter. If you want to define the parameter as optional you can use theUrlParameter.Optional enum.

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 the displaycustomer function.

 Collapse | Copy Code

routes.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 Code

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

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

Page 33: Learn MVC.docx

"{controller}/{action}/{id}" defines that the 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 an MVC URL. All actions to MVC come via MVC URL and even the 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 URLs.

For instance let’s consider the MVC URL http://localhost/Customer/ViewCustomer. If anyone wants to view customer details for the 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 likehttp://localhost/Customer/ViewCustomer/Shiv is invalid. The 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 step is to create a simple customer class model which will be invoked by the controller.

 Collapse | Copy Code

public class Customer{public int Id { set; get; }public string CustomerCode { set; get; }public double Amount { set; get; }}

Step 2: Create the controller class

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

 Collapse | Copy Code

public class CustomerController : Controller{List<Customer> Customers = new List<Customer>();//// GET: /Customer/public CustomerController(){Customer obj1 = new Customer();obj1.Id = 12;

Page 34: Learn MVC.docx

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);}}

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 to 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 routesThe validation described in the step 2 can be achieved by applying a regular expression on the route map. If you go to the global.asax file and see the maproute function, the input to this function is the constraint as shown in the below figure.

In case you are new to regular expressions, 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 themaproute function as shown below. ‘\d{1,2}’ in regex means that the input should be numeric and should be a maximum of length 1 or 2 , i.e., between 0 to 99.

Page 35: Learn MVC.docx

You can specify the 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 Code

routes.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 worksSo 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 an 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.

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.

Page 36: Learn MVC.docx

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 labOne of the crucial things in any website development is defining navigations from one page to another page. In MVC everything is an action and those actions invoke the views or pages. We can not specify direct hyperlinks likewww.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 URLs.

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

Lab 9: Understanding MVC outbound URLsIntroduction

When we talk about web applications, end users would like to navigate from one page to another 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 a hyper link page name and things should be fine.By doing that you are violating MVC principles. MVC principles say that the 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 37: Learn MVC.docx

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 viewsLet's create three views as shown in the below figure Home, About, and Product.

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

Page 38: Learn MVC.docx

Step 2: Create controller for the viewsThe next step is to define controller actions which will invoke these views. In the below code snippet we have defined three actions: GotoHome (this invokes the home view), Aboutus (this invokes the about view), and SeeProduct (this invokes the product view).

 Collapse | Copy Code

public 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 Code

This is products<a href="GotoHome">Go Home</a><br />

Page 39: Learn MVC.docx

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

This is About us<a href="GotoHome">Go Home</a><br /><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 /></div>

Step 4: Enjoy your navigation

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

Page 40: Learn MVC.docx

While navigating you can see how the URLs are pointing to the actions rather than absolute page names likehome.aspx, aboutus.aspx, etc., which violates the complete MVC principle.

What’s for the third day?In the third session, we will talk about Partial views, Validation using data annotations, Razor (MVC 3), MVC Windows Authentication, MVC Forms Authentication and a lot more. The next lab will be a bit more advanced as compared to the second day. Below is the link for the third day: Click here for the day third MVC step by step.A final note: you can watch my .NET interview questions and answers videos on various topics like WCF, Silverlight, LINQ, WPF, Design Patterns, Entity Framework etc.

Page 41: Learn MVC.docx

Learn MVC (Model View Controller) Step by Step in 7 Days – Day 3 [3]

Introduction So, what’s the agenda? Day 1: Controllers, strong typed views, and helper classes Day 2: Unit test, routing,   and outbound URLs Lab 10: Partial views o Step 1: Create a simple view o Step 2: Create a simple partial view o Step 3: Put something in the partial view o Step 4: Call the partial view in the main o Step 5: Run the program and see the action Lab 11: Validation using Data Annotation o Step 1: Decorate model with data annotation o Step 2: Change the ASPX code o Step 3: Enable client validation o Step 4: Write your controller logic o Step 5: Run your application to see the action o Summary of other data annotation attributes Lab 12: MVC 3: Razor o Step 1: Install MVC 3 and create a project using the same o Step 2: Select Razor o Step 3: Add a view and invoke the same from   the controller o Step 4: Practice Razor syntaxes 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) o Step 1: Enable Windows Authentication o Step 2: Just some defects o Step 3: Apply Authorize tags on your controllers / actions o Step 4: Create setup o Step 5: Create IIS application o Step 6: Publish o Step 7: Run the controller and action Lab 14:- MVC Security   (Forms Authentication) o Step 1:- Define the Login   page controller o Step 2:- Create the index view o Step 3:- Validate credentials o Step 4:- Authorize attribute o Step 5:- Change “Web.config” file o Step 6:- See Forms   authentication in action What’s for the fourth day? 50 MVC Interview questions with answers Are you completely new to MVC?

Page 42: Learn MVC.docx

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 theDay 2 and Day 4 articles you can start from Day 1 - Learn MVC ASP.NET step by step .

o Partial views.o Validations using data annotations.o Razor (MVC 3).o MVC Windows authenticationo 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 classesIf 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 URLsSee here what we did in Day 2 of MVC so that we can get in synch. 

Lab 10: Partial viewsWhen 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 43: Learn MVC.docx

Step 1: Create a simple viewThe 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.

Page 44: Learn MVC.docx

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 mainFinally 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>

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.

Page 45: Learn MVC.docx

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

Page 46: Learn MVC.docx

Step 1: Decorate model with data annotation

Import the data annotation namespace as shown in the code snippet below.

 Collapse | Copy Code

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.

 Collapse | Copy Code

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.

 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.

 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(); %>

Page 47: Learn MVC.docx

</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 logicFrom 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");}}

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.

Page 48: Learn MVC.docx

 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 Code

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

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.

 Collapse | Copy Code

TryUpdateModel(NewCustomer);

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

 Collapse | Copy Code

ModelState.AddModelError("FirstName", "This is my server-side error.");

Lab 12: MVC 3: RazorTill 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.

Page 49: Learn MVC.docx

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

o The Empty option creates a project with the least amount of files.o The Internet Application option creates a shell application which includes user registration and

authentication, navigation, and a consistent visual style.o 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 50: Learn MVC.docx

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.

Page 51: Learn MVC.docx

 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 codeIf 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 Code

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?

 Collapse | Copy Code

Page 52: Learn MVC.docx

<%=DateTime.Now%>

Practice 2: Multiple lines of codeIf 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 />}

 Collapse | Copy Code

@if (DateTime.Now.Year.Equals(2011)){

Page 53: Learn MVC.docx

// 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 Code

@[email protected]

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 Code

Tweet me @@Shivkoirala

Practice 6: HTML display with RazorIn 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).

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

Page 54: Learn MVC.docx

@{ 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.

Page 55: Learn MVC.docx

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 defectsIn MVC 3 template, there is a small defect. It runs forms authentication by default. Set the below tags in  theappsettings 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>

Step 3: Apply Authorize tags on your controllers / actionsOnce 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")]

Page 56: Learn MVC.docx

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.

Page 57: Learn MVC.docx

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.

Page 58: Learn MVC.docx

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.

Page 59: Learn MVC.docx

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 Code

public ActionResult Index(){return View();}

Step 2:- Create the index viewThe 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(); }

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 Code

if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123")){…..}

Page 60: Learn MVC.docx

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 Code

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. 

 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.

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. 

Page 61: Learn MVC.docx

 

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.

50 MVC Interview questions with answersIn case you are going for interviews you can read my 50 Important MVC interview questions with answer articlehttp://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.

Page 62: Learn MVC.docx

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 

Page 63: Learn MVC.docx

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

Page 64: Learn MVC.docx

Learn MVC (Model view controller) Step by Step in 7 days – Day 4 [4]

Contents 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 controllers Lab 15:- JSON , MVC and Jquery o Step 1 :- Create a simple Customer model o Step 2 :- Expose Customer object as JSON o Step 3 :- Consume the JSON controller in jquery o Step 4 :- Run the application and see the data Lab 16:- Session management in MVC (ViewData,ViewBag,TempData and session variables) o Step 1:- Create two controllers “DefaultController1” and “DefaultController2”. o Step 2 :- Set Session , tempdata , viewdata and viewbag o Step 3:- Read Session,tempdata ,viewdata and viewbag values Lab 17:- Asynch controllers o Step 1 :- Inherit from AsyncController class o Step 2 :- Mark methods with Async appended o Step 3 :- Create the completed method o Step 4:- Ensure to create “SomeHeavyMethod.aspx” view o Step 5 :- Run and enjoy What’s for Fifth day? 50 MVC Interview questions with answers Are you completely new to MVC?

So, what’s the agenda?.In day 4 we will look in to JSON ,Jquery ,Aysnch controllers and session management with MVC.

Day 1:-Controllers, strong typed views and helper classeshttp://www.codeproject.com/Articles/207797/Learn-MVC-Model-view-controller-Step-by-Step-in-7

Day 2:- Unit test,routing and outbound URLShttp://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7

Page 65: Learn MVC.docx

Day 3:- Partial views, Data annotations,Razor , Authentication and Authorizationhttp://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-7

Lab 15:- JSON , MVC and JqueryIn case you are new to JSON please read this before moving ahead with this lab ,What is JSON ?.

So in this lab we will expose a simple “Customer” object from MVC in JSON format and consume the same using Jquery.

For this lab please ensure that the project is created by using basic project template so that the necessary Jquery libraries are included with the MVC project.

Step 1 :- Create a simple Customer model

So the first step is to create a simple “Customer” class in the MVC project. 

 Collapse | Copy Code

public class Customer { private string _CustomerCode; public string CustomerCode { get { return _CustomerCode; } set { _CustomerCode = value; } } }

Step 2 :- Expose Customer object as JSONTo expose the customer object in JSON format we need to use “JsonResult” as shown in the below code snippet.

 Collapse | Copy Code

public JsonResult getJson(){ Customer obj = new Customer();

Page 66: Learn MVC.docx

obj.CustomerCode = "c001"; return Json(obj,JsonRequestBehavior.AllowGet);}

Please do once run the controller withthe above JSON action to check if the JSON result is displayed properly. If you are using chrome the display comes on the browser , if its internet explorer it spits out a file.

   

Step 3 :- Consume the JSON controller in jquery In case you are new to Jquery , please read this What is jquery ?

The next step is to consume the JSON data in Jquery using MVC view. So go ahead and add a view for example my view name is “LearnJquery.aspx”.

First thing add the Jquery library at the top of the ASPX page. In case you do not find jquery library in your project that means you have not created the MVC project using the basic template.

 Collapse | Copy Code

<script src="../../Scripts/jquery-1.8.2.js"></script>

You can then make a call the controller which is exposing in JSON format using “getJson” method as shown below. Its takes three parameters:-

o The first parameter in “getJson” is the MVC JSON URL with complete controller/action path format.

o The second parameter is the data to be passed. For now its NULL as we are more interesting in getting JSON data rather posting data.

o The last parameter is the call back method (“Display”) which will be invoked once we get the JSON data from the controller. The “Display” function is also available in the below code snippet. I am just putting an alert with the property name. FYI you can see how I have just typed “data.CustomerCode” , no parsing nothing the JSON data is automatically translated to javascript object. 

 Collapse | Copy Code

$.getJSON("/Json/getJson", null, Display);function Display(data){alert(data.CustomerCode);}

The complete MVC view HTML looks as shown below. I have created a simple HTML button and on the click event I am calling a “getJson” javascript method which makes a call to the JSON controller and displays the JSON data in a javascript alert.

 Collapse | Copy Code

<script language="javascript">

Page 67: Learn MVC.docx

function getJson() { $.getJSON("/Json/getJson", null, Display); return true; } function Display(data) { alert(data.CustomerCode); }</script><input type="button" value="See Json data" onclick="return getJson();"/>

This view I have invoked by using “DisplayJson” action.

 Collapse | Copy Code

public class JsonController : Controller{ public ActionResult DisplayJson() { return View("LearnJquery"); }}

Step 4 :- Run the application and see the data

After you have done all the hardwork its time to hit the “DisplayJson” action to see the beauty running.

 

Lab 16:- Session management in MVC (ViewData,ViewBag,TempData and session variables)The primary goal of MVC is to create web applications and web applications use HTTP protocol. Now HTTP protocol is a stateless by nature. So when you send a request to MVC application it serves the request and forgets about the request. Next time when the same user sends the request MVC treats that as a complete new request.

Now think about the below situation:-

Page 68: Learn MVC.docx

o End user sends request to a MVC site.o MVC sends a login page.o User enters proper details and sends data to the MVC application.o MVC validates the user and sends home page of the site. MVC application now forgets

everything about the user as it’s stateless.o Now user clicks on one of the home page links. This is sent to the MVC application and because

MVC application has forgotten everything about the user, he sends a login page again for authentication….User would feel Weird…

In short we need to have some kind of mechanism which will help us to remember states between request and response of MVC.

There are 3 ways of maintaining states in MVC and these ways can be used depending from which layer to which layer you navigate.

Temp data: -Helps to maintain data on redirects for a single request and response. Now the redirects can be from controller to controller or from controller to view.

View data: - Helps to maintain data when you move from controller to view.View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Page 69: Learn MVC.docx

Session variables: - By using session variables we can maintain data until the browser closes.

Let’s demonstrate the above fundamental with a demo.

Step 1:- Create two controllers “DefaultController1” and “DefaultController2”.

Add two controllers “DefaultController1” and “DefaultController2”. 

 

Step 2 :- Set Session , tempdata , viewdata and viewbag

In the “Default1Controller” in “Action1” we set session,tempdata,viewdata and viewbag values as shown in the below code snippet. Once we set the values we do a redirect to the action “SomeOtherAction” which belongs to “Controller2”.

 Collapse | Copy Code

public class Default1Controller : Controller { // // GET: /Default1/ public ActionResult Action1() { Session["Session1"] = "UntilBrowserCloses"; TempData["FortheFullRequest"] = "FortheFullRequest"; ViewData["Myval"] = "ControllertoView"; ViewBag.MyVal = "ControllertoView"; return RedirectToAction("SomeOtherAction","Default2"); } }

Step 3:- Read Session,tempdata ,viewdata and viewbag values

In “Default2Controller” we will try to read values set in “Default1Controller”. Once the values are read we invoke a view called as “SomeView”.

Please note I am setting “ViewData” and “ViewBag” before redirecting to the view.

 Collapse | Copy Code

public class Default2Controller : Controller { // // GET: /Default2/ public ActionResult SomeOtherAction()

Page 70: Learn MVC.docx

{ string str = Convert.ToString(TempData["FortheFullRequest"]); string str2 = Session["Session1"].ToString(); string str3 = Convert.ToString(ViewData["Myval"]); ViewData["Myval"] = "ControllertoView";ViewBag.MyVal = "ControllertoViewCollection"; return View("SomeView"); } }

The “SomeView”view justdisplays the data present in “TempData” ,”ViewData” , “ViewBag” and “Session” .

 Collapse | Copy Code

<%= TempData["FortheFullRequest"] %><br /><%= ViewData["Myval"] %><br /><%= Session["Session1"] %><%= ViewBag.MyVal %><a href="/Default1/Action1">Click</a>

So let’s put debug points in both the controller actions and let’s hit Default1 controller and Action1 actionhttp://localhost:1203/Default1/Action1 . So in this action session,tempdata ,viewdata and viewbag are loaded. Below is how the watch window looks with data. 

   

Now from here we are redirecting to controller2 action “SomeOtherAction”.

In controller2 you can see get “TempData” and “Session” variables but not “ViewBag” and “ViewData”( See “str3” and “str4” are set to null). In other words “ViewData” and “ViewBag” do not persist data in redirects while “TempData” and “Session” variables do.

I have set “ViewData” and “ViewBag” with some data again before invoking the view “SomeView”.

Page 71: Learn MVC.docx

When the view gets invoked we can see all the data. In other words “ViewData” and “ViewBag” persist data from controller to view. And also tempdata and session have persisted data.

 

Now when the view invokes I have kept a click hyper link which invokes “Action1” from “Controller1”. This is to simulate a fresh request.

 

When we click on the link. All the other variables go off only session variables persist, see the below figure. It means “Session” variables can persist between requests.

Page 72: Learn MVC.docx

 

Below is a summary table which shows different mechanism of persistence.

Maintains data between

ViewData/ViewBagTempData ( For single request)

Session

Controller to Controller

No Yes Yes

Controller to View Yes Yes Yes

View to Controller No No Yes

Lab 17:- Asynch controllersMVC applications at the end of the day are web applications which are hosted inside IIS.Now when any request comes to MVC controller it pulls up a thread from thread pool and serves that request. In other words IIS web server maintains a pool of threads rather than creating threads from scratch again and again to gain performance benefits.Let’s assume that a web server has a thread pool size of 2. Now this is just an assumption because a pool size of two is very much hypothetical. But to make things simple consider that the thread pool size is 2.

Page 73: Learn MVC.docx

So let’s say first request comes to the site, IIS pulls up a readymade thread object from the thread pool and starts serving that request. In the meantime let’s say second request comes in so again IIS pulls up a thread from the thread pool and starts serving the second request.

Now the fun starts when third request comes in. The IIS webserver does not have any more thread objects in the pool as those are already serving “request1” and “request2”. So he just moves the third request in to a waiting mode or the server can send “503 busy” message to the client.

This situation is termed as “Thread Starvation”. Thread starvation situations can be overcome by making the request “Asynchronous”. So the request comes in and immediately the request is processed in an “Asynch” manner and releasing the thread serving the request immediately.

So to avoid this we can achieve the same by making our controllers “Asynch”.

Below is a nice video which demonstrates MVC Thread starvation. 

So let’s understand step by step how to implement MVC Asynch controllers.

Step 1 :- Inherit from AsyncController class

Consider the below controller class “HeavyController” which has an action “SomeHeavyMethod” and this action waits for 20 seconds. So let understand how we can make this simple controller aasynch controller.

 Collapse | Copy Code

public class HeavyController : Controller{ // // GET: /Heavy/ public ActionResult SomeHeavyMethod() {

Page 74: Learn MVC.docx

Thread.Sleep(20000); return View(); }}

 So the first step is to inherit from “AsyncController” class.

 Collapse | Copy Code

public class HeavyController : AsyncController{}

Step 2 :- Mark methods with Async appended

The next step is to append “Async” word after the methods. So you can see “SomeHeavyMethod” has been changed to “SomeHeavyMethodAsync”.

The heavy logic code i.e. “Thread.Sleep” is moved to a different method and that method is invoked using task parallel library from the “SomeHeavyMethodAsync”.

Every time a “Task” or a “Thread” is started we increment the outstanding operations counter by using “AsynchManager” and every time a multi-threaded task is completed we decrement the counter.

 Collapse | Copy Code

public class HeavyController : AsyncController{public void SomeHeavyMethodAsync(){AsyncManager.OutstandingOperations.Increment();Task.Run(new Action(Heavy));}public void Heavy(){Thread.Sleep(20000);AsyncManager.OutstandingOperations.Decrement();}}

Step 3 :- Create the completed method

Now once all the multi-threaded tasks complete and the outstanding operations are zero we need to return the view. So for the same we need to create an action result method with “Completed” word appended. This method gets called when all outstanding operations are zero.

 Collapse | Copy Code

public ActionResult SomeHeavyMethodCompleted(){ return View();}

Step 4:- Ensure to create “SomeHeavyMethod.aspx” view

Also ensure you add “SomeHeavyMethod” view with some text on it.

Page 75: Learn MVC.docx

 Collapse | Copy Code

<html><head runat="server"><meta name="viewport" content="width=device-width" /><title>Some heavy method</title></head><body><div> This is loaded after some time....</div></body></html>

Step 5 :- Run and enjoyNow try hitting “Heavy/SomeHeavyMethod” and see the output. I would suggest you to measure “Thread queued” to see the benefit of asynch controller. Watch this video to see how to measure “Thread Queued” http://www.youtube.com/watch?v=wvg13n5V0V0.

What’s for Fifth day?Still working on it.

Final note, you can watch my c# and MVC training videos on various sections like WCF, Silver light, LINQ, WPF, Design patterns, Entity framework etc. By any chance do not miss my .NET and c# interview questions and answers book from www.questpond.com   .

Page 76: Learn MVC.docx

(Model view controller)MVC Interview questions and answers [5]

Disclaimer  

By reading these MVC interview question it does not mean you will go and clear MVC interviews. The whole purpose of this article is to quickly brush up your MVC knowledge before you for the MVC interviews.

This article does not teach MVC, it’s a last minute revision sheet before going for MVC interviews.

In case you want to learn MVC from scratch start by reading Learn MVC ( Model view controller) step by step 7 daysor you can also start with my step by step MVC ( Model view controller) video series from youtube.What is MVC(Model view controller)?

MVC is architectural pattern which separates the representation and the user interaction. It’s divided in three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task.

The “View” is responsible for look and feel. “Model” represents the real world object and provides data to the “View”. The “Controller” is responsible to take the end user request and load the appropriate “Model”

and “View”.

 

Figure: - MVC (Model view controller)Can you explain the complete flow of MVC? 

Below are the steps how control flows in MVC (Model, view and controller) architecture:-

All end user requests are first sent to the controller. The controller depending on the request decides which model to load. The controller loads the

model and attaches the model with the appropriate view. The final view is then attached with the model data and sent as a response to the end user on

the browser.

Page 77: Learn MVC.docx

Is MVC suitable for both windows and web application?

MVC architecture is suited for web application than windows. For window application MVP i.e. “Model view presenter” is more applicable.IfyouareusingWPFandSLMVVMismoresuitableduetobindings.

What are the benefits of using MVC?

There are two big benefits of MVC:-

Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.

Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.

Is MVC different from a 3 layered architecture?

MVC is an evolution of a 3 layered traditional architecture. Many components of 3 layered architecture are part of MVC.  So below is how the mapping goes.

Functionality3 layered / tiered architecture

Model view controller architecture

Look and Feel User interface. View.

UI logic User interface. Controller

Business logic /validations Middle layer Model.

Request is first sent to User interface Controller.

Accessing data Data access layer. Data access layer.

Page 78: Learn MVC.docx

Figure: - 3 layered architectureWhat is the latest version of MVC? 

When this note was written, four versions where released of MVC. MVC 1 , MVC 2, MVC 3 and MVC 4. So the latest is MVC 4. 

What is the difference between each version of MVC?

Below is a detail table of differences. But during interview it’s difficult to talk about all of them due to time limitation. So I have highlighted important differences which you can run through before the interviewer.

MVC 2  MVC 3 MVC 4 

Client-Side Validation Templated Helpers Areas Asynchronous ControllersHtml.ValidationSummary Helper Method DefaultValueAttribute in Action-Method Parameters Binding Binary Data with Model Binders DataAnnotations Attributes Model-Validator Providers New RequireHttpsAttribute Action Filter Templated Helpers Display Model-Level Errors

Razor

Readymade project templates

HTML 5 enabled templatesSupport for Multiple View EnginesJavaScript and Ajax

Model Validation Improvements

ASP.NET Web API

Refreshed and modernized default project templatesNew mobile project template

Many new features to support mobile apps

Enhanced support for asynchronous methods

What are routing in MVC? 

Routing helps you to define a URL structure and map the URL with the controller.

For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”,  it goes to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.

 Collapse | Copy Code

routes.MapRoute( "View", // Route name "View/ViewCustomer/{id}", // URL with parameters new { controller = "Customer", action = "DisplayCustomer", id = UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code written?

The route mapping code is written in the “global.asax” file.

Can we map multiple URL’s to the same action?

Yes , you can , you just need to make two entries with different key names and specify the same controller and action.

How can we navigate from one view to other view using hyperlink?

By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Page 79: Learn MVC.docx

 Collapse | Copy Code

<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be invoked only by GET or POST?

We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.

 Collapse | Copy Code

[HttpGet] public ViewResult DisplayCustomer(int id) { Customer objCustomer = Customers[id]; return View("DisplayCustomer",objCustomer); }

How can we maintain session in MVC?

Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

What is the difference between tempdata ,viewdata and viewbag?

 

Figure:- difference between tempdata , viewdata and viewbagTemp data: -Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect,“tempdata” helps to maintain data between those redirects. It internally uses session variables.View data: - Helps to maintain data when you move from controller to view.View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Page 80: Learn MVC.docx

Figure:-dynamic keywordSession variables: - By using session variables we can maintain data from any entity to any entity.Hidden fields and HTML controls: - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Below is a summary table which shows different mechanism of persistence.

Maintains data between

ViewData/ViewBag

TempData Hidden fields Session

Controller to Controller

No Yes No Yes

Controller to View Yes No No Yes

View to Controller No No Yes Yes

What are partial views in MVC? 

Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header and footer as shown in the image below.

Figure:- partial views in MVC

Page 81: Learn MVC.docx

For every page you would like to reuse the left menu, header and footer controls. So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

How did you create partial view and consume the same?

When you add a view to your project you need to check the “Create partial view” check box.

Figure:-createpartialview

Once the partial view is created you can then call the partial view in the main view using “Html.RenderPartial” method as shown in the below code snippet.

 Collapse | Copy Code

<body><div><% Html.RenderPartial("MyView"); %></div></body>

How can we do validations in MVC? 

One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “customer” class with a property “customercode”.

This”CustomerCode” property is tagged with a “Required” data annotation attribute. In other words if this model is not provided customer code it will not accept the same.

 Collapse | Copy Code

public class Customer

Page 82: Learn MVC.docx

{ [Required(ErrorMessage="Customer code is required")] public string CustomerCode { set; get; } }

In order to display the validation error message we need to use “ValidateMessageFor” method which belongs to the “Html” helper class.

 Collapse | Copy Code

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post)){ %><%=Html.TextBoxFor(m => m.CustomerCode)%><%=Html.ValidationMessageFor(m => m.CustomerCode)%><input type="submit" value="Submit customer data" /><%}%>

Later in the controller we can check if the model is proper or not by using “ModelState.IsValid” property and accordingly we can take actions. 

 Collapse | Copy Code

public ActionResult PostCustomer(Customer obj){if (ModelState.IsValid){ obj.Save(); return View("Thanks");}else{ return View("Customer");}}

Below is a simple view of how the error message is displayed on the view.

Figure:- validations in MVCCan we display all errors in one go?

Yes we can, use “ValidationSummary” method from HTML helper class.

 Collapse | Copy Code

Page 83: Learn MVC.docx

<%= Html.ValidationSummary() %>

What are the other data annotation attributes for validation in MVC?

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 regular expression, you can use “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; }

Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.

 Collapse | Copy Code

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.

 Collapse | Copy Code

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.

 Collapse | Copy Code

TryUpdateModel(NewCustomer);

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

 Collapse | Copy Code

ModelState.AddModelError("FirstName", "This is my server-side error.");

Page 84: Learn MVC.docx

How can we enable data annotation validation on client side?

It’s a two-step process first reference the necessary jquery files.

 Collapse | Copy Code

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script><script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script><script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>

Second step is to call “EnableClientValidation” method. 

 Collapse | Copy Code

<% Html.EnableClientValidation(); %>

What is razor in MVC? 

It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was introduced in MVC 3.

Why razor when we already had ASPX?

Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write. 

 Collapse | Copy Code

<%=DateTime.Now%>

In Razor it’s just one line of code.

 Collapse | Copy Code

@DateTime.Now

So which is a better fit Razor or ASPX?

As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes.

How can you do authentication and authorization in MVC?

You can use windows or forms authentication for MVC.

How to implement windows authentication for MVC?

For windows authentication you need to go and modify the “web.config” file and set authentication mode to windows.

 Collapse | Copy Code

<authentication mode="Windows"/>

Page 85: Learn MVC.docx

<authorization><deny users="?"/></authorization>

Then in the controller or on the action you can use the “Authorize” attribute which specifies which users have access to these controllers and actions. Below is the code snippet for the same. Now only  the users specified in the controller and action can access the same.

 Collapse | Copy Code

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")] public class StartController : Controller { // // GET: /Start/ [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")] public ActionResult Index() { return View("MyView"); } }

How do you implement forms authentication in MVC?

Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.

 Collapse | Copy Code

<authentication mode="Forms"><forms loginUrl="~/Home/Login" timeout="2880"/></authentication>

We also need to create a controller where we will check the user is proper or not. If the user is proper we will set the cookie value.

 Collapse | Copy Code

public ActionResult Login(){if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123")){ FormsAuthentication.SetAuthCookie("Shiv",true); return View("About");}else{ return View("Index");}}

All the other actions need to be attributed with “Authorize” attribute so that any unauthorized user if he makes a call to these controllers it will redirect to the controller ( in this case the controller is “Login”) which will do authentication.

 Collapse | Copy Code

Page 86: Learn MVC.docx

[Authorize]PublicActionResult Default(){return View();}[Authorize]publicActionResult About(){return View();}

How to implement Ajax in MVC?

You can implement Ajax in two ways in MVC: - 

Ajax libraries Jquery

Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the submit action click will be an asynchronous ajax call.

 Collapse | Copy Code

<script language="javascript">function OnSuccess(data1) {// Do something here}</script><div><% var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"}; %><% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %><input id="txtCustomerCode" type="text" /><br /><input id="txtCustomerName" type="text" /><br /><input id="Submit2" type="submit" value="submit"/></div><%} %>

In case you want to make ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as shown in the below code.

Figure:- implement Ajax in MVC

Page 87: Learn MVC.docx

So if you want to create Ajax asynchronous   hyperlink by name “GetDate” which calls the “GetDate” function on the controller , below is the code for the same.  Once the controller responds this data is displayed in the HTML DIV tag by name “DateDiv”.

 Collapse | Copy Code

<span id="DateDiv" /><%: Ajax.ActionLink("Get Date","GetDate",new AjaxOptions {UpdateTargetId = "DateDiv" })%>

Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.

 Collapse | Copy Code

public class Default1Controller : Controller{ public string GetDate() { Thread.Sleep(10000); return DateTime.Now.ToString(); }}

The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we are making an ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$.post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyper link click event as you want.

 Collapse | Copy Code

function GetData() { var url = "/MyAjax/getCustomer"; $.post(url, function (data) { $("#txtCustomerCode").val(data.CustomerCode); $("#txtCustomerName").val(data.CustomerName); } ) }

What kind of events can be tracked in AJAX?  

Figure:- tracked in AJAX

Page 88: Learn MVC.docx

What is the difference between “ActionResult” and “ViewResult”?

“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult” and so on.

“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.

 Collapse | Copy Code

public ActionResult DynamicView(){ if (IsHtmlView) return View(); // returns simple ViewResult else return Json(); // returns JsonResult view}

What are the different types of results in MVC? Collapse | Copy Code

Note: -It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest.

There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that canhave11subtypes’sas listed below: - 

1. ViewResult - Renders a specified view to the response stream2. PartialViewResult - Renders a specified partial view to the response stream3. EmptyResult - An empty response is returned4. RedirectResult - Performs an HTTP redirection to a specified URL5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the

routing engine, based on given route data6. JsonResult - Serializes a given ViewData object to JSON format7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client8. ContentResult - Writes content to the response stream without requiring a view9. FileContentResult - Returns a file to the client10.FileStreamResult - Returns a file to the client, which is provided by a Stream11.FilePathResult - Returns a file to the client

What are “ActionFilters”in MVC?

“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed.

Page 89: Learn MVC.docx

Figure:- “ActionFilters”in MVC

Action filters are useful in the following scenarios:-

1. Implement post-processinglogicbeforethe action happens.2. Cancel a current execution.3. Inspect the returned value.4. Provide extra data to the action.

You can create action filters by two ways:-

Inline action filter. Creating an “ActionFilter” attribute.

To create a inline action attribute we need to implement “IActionFilter” interface.The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement pre-processing logic or cancellation logic in these methods.

 Collapse | Copy Code

public class Default1Controller : Controller , IActionFilter { public ActionResult Index(Customer obj) { return View(obj); } void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { Trace.WriteLine("Action Executed"); } void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { Trace.WriteLine("Action is executing"); } }

The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in the below code.

 Collapse | Copy Code

Page 90: Learn MVC.docx

public class MyActionAttribute : ActionFilterAttribute , IActionFilter{void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext){ Trace.WriteLine("Action Executed");}void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext){ Trace.WriteLine("Action executing");}}

Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the “Default1Controller” with “MyActionAttribute” class which was created in the previous code.

 Collapse | Copy Code

[MyActionAttribute]public class Default1Controller : Controller { public ActionResult Index(Customer obj) { return View(obj); }}

Can we create our custom view engine using MVC?

Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to follow 3 steps:-

Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time. 

Step 1:- We need to create a class which implements “IView” interface. In this class we should write the logic of how the view will be rendered in the “render” function. Below is a simple code snippet for the same.

 Collapse | Copy Code

public class MyCustomView : IView { private string _FolderPath; // Define where our views are stored public string FolderPath { get { return _FolderPath; } set { _FolderPath = value; } }

public void Render(ViewContext viewContext, System.IO.TextWriter writer) { // Parsing logic <dateTime> // read the view file string strFileData = File.ReadAllText(_FolderPath); // we need to and replace <datetime> datetime.now value string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString()); // this replaced data has to sent for display writer.Write(strFinal); } }

Page 91: Learn MVC.docx

Step 2 :-We need to create a class which inherits from “VirtualPathProviderViewEngine” and in this class we need to provide the folder path and the extension of the view name. For instance for razor the extension is “cshtml” , for aspx the view extension is “.aspx” , so in the same way for our custom view we need to provide an extension. Below is how the code looks like. You can see the “ViewLocationFormats” is set to the “Views” folder and the extension is “.myview”.

 Collapse | Copy Code

public class MyViewEngineProvider : VirtualPathProviderViewEngine { // We will create the object of Mycustome view public MyViewEngineProvider() // constructor { // Define the location of the View file this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; //location and extension of our views } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath); MyCustomView obj = new MyCustomView(); // Custom view engine class obj.FolderPath = physicalpath; // set the path where the views will be stored return obj; // returned this view paresing logic so that it can be registered in the view engine collection } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath); MyCustomView obj = new MyCustomView(); // Custom view engine class obj.FolderPath = physicalpath; // set the path where the views will be stored return obj; // returned this view paresing logic so that it can be registered in the view engine collection } }

Step 3:- We need to register the view in the custom view collection. The best place to register the custom view engine in the “ViewEngines” collection is the “global.asax” file. Below is the code snippet for the same.

 Collapse | Copy Code

protected void Application_Start() { // Step3 :- register this object in the view engine collection ViewEngines.Engines.Add(new MyViewEngineProvider());<span class="Apple-tab-span" style="white-space: pre; "> </span>…..}

Below is a simple output of the custom view written using the commands defined at the top.

Figure:-customviewengineusingMVC

If you invoke this view you should see the following output.

Page 92: Learn MVC.docx

How to send result back in JSON format in MVC?

In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a simple sample code which returns back “Customer” object in JSON format using “JsonResult”.

 Collapse | Copy Code

public JsonResult getCustomer(){Customer obj = new Customer();obj.CustomerCode = "1001";obj.CustomerName = "Shiv"; return Json(obj,JsonRequestBehavior.AllowGet);}

Below is the JSON output of the above code if you invoke the action via the browser.

What is “WebAPI”?

HTTP is the most used protocol.For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile,javascripts,windows  application etc.

For satisfying the broad range of client “REST” was the proposed approach. You can read more about “REST” from WCF chapter.

“WebAPI” is the technology by which you can expose data over HTTP following REST principles.

But WCF SOAP also does the same thing, so how does “WebAPI” differ?SOAP WEB API

SizeHeavy weight because of complicated WSDL structure.

Light weight, only the necessary information is transferred.

ProtocolIndependent of protocols. Only  for HTTP protocol

Formats

To parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call.

Output of “WebAPI” are simple string message,JSON,Simple XML format etc. So writing parsing logic for the same in very easy.

Page 93: Learn MVC.docx

Principles

SOAP follows WS-* specification.WEB API follows REST principles. (Please refer about REST in WCF chapter).

With WCF also you can implement REST,So why "WebAPI"?

WCF was brought in to implement SOA, never the intention was to implement REST."WebAPI'" is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

How to implement “WebAPI” in MVC?

Below are the steps to implement "webAPI" :- 

Step1:-Create the project using the "WebAPI" template.

Figure:- implement “WebAPI” in MVCStep 2:- Once you have created the project you will notice that the controller now inherits from "ApiController" and you can now implement "post","get","put" and "delete" methods of HTTP protocol.

 Collapse | Copy Code

public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { }

Page 94: Learn MVC.docx

}

Step 3:-If you make a HTTP GET call you should get the below results.

Figure:- HTTPFinally do not forget to visit my video site which covers lots of C# interview questions and answers: -www.questpond.com

Page 95: Learn MVC.docx

References

[1] http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in-7 [2] http://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7 [3] http://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-7 [4] http://www.codeproject.com/Articles/667841/Learn-MVC-Model-view-controller-Step-by-Step-in-7 [5] http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and