Learn MVC (Model view controller) Step by Step in 7 days - Day 3

So, what's the agenda?

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

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

  • Partial views.
  • Validations using data annotations.
  • Razor (MVC 3).

a1.jpg
 

So let's start with the above 3 labs one by one.

FYI: - In case you are complete new to MVC (Model view controller), please see the last section of the article for kick start.

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

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

Day 2 :- Unit test, routing and outbound URLS

Here see what we did inDay 2 of MVC so that we can get into the synch.

Lab 10:- Partial views

When we talk about web application reusability is the key. So as a MVC developer we would like to create reusable views. For instance we would like to create reusable views like footer and header views and use them inside one big MVC view.

Reusable views can be achieved by creating "Partial views".

a2.jpg
 

Step 1:- Create a simple view

The first step would be to create a simple view with a controller. You can see from the below snapshot, I have created a simple view called as "Index.aspx" which will be invoked via "Homecontroller.cs".

a3.jpg
 

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.

a4.jpg
 

Step 3:- Put something in partial view

Put some text or logic in partial view.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" 
%>
This is reusable view

Step 4:- Call the partial view in the main

Finally call the partial view in the main view using "Html.RenderPartial" function and pass the view name in the function as shown in the below code snippet.

c2.jpg

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.

a5.jpg
 

Step 5:- Run the program and see the action.

Finally do a CNTRL + f5, put the proper controller path and see your hard work result. Below is the snapshot ofhow things should look like.

a6.jpg
 

Lab 11:- Validation using Data Annotation

Validating data is one of the key things in any web application. As a developer you would like to run validation both on the client side (browser) and also on the server side.

So you would probably like to write the validation once and then expect the validation framework to generate the validation logic on both the ends.

Good news, this is possibleby 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 providedproper ?, are values in range ?etc.

Data annotations are nothing but the metadata which you can apply on the model and the MVC framework will validate using the metadata provided.

In this lab let's enforce validation by using data annotation. So the first thing is use Lab 4 and create a simple model and a strong typed data entry view. In case you have come to this lab straight forward, please once have a look at day 1 labs, before proceeding ahead.

So assuming you have created the model and the strong typed view, let's start applying data annotations.

Note: - The view created should be a strong typed view.

Step 1:- Decorate model with data annotation

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

 using System.ComponentModel.DataAnnotations;

Let say we have a customer model and we want to ensure that the customer code field is compulsory. So you can apply attribute "Required" as shown in the below code snippet. If the validation fails and you would like to display some error message, you can pass the "ErrorMessage" also.

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

Step 2:- Change the ASPX code

Now there are some code changes we would be doing in the ASPX code as compared to our previous lab. Inside the body we would like to display error message if the data is not proper. This is done by using the below code snippet.

<%= Html.ValidationSummary() %>

We also need to code our HTML form to input data. Below is the code snippet for the same. Please note the "EditorForModel" function will automatically generate UI controls looking at the model properties. So we do not need to create control individually as we did for Lab 4.

 <% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %><%= Html.EditorForModel() 
%>
<%}%>

Step 3:- Enable Client validation

As said previously we would like to fire validation on both server and client side. In order to fire validations on the client side, we need to refer three JavaScript files as shown in the below code snippet.

c1.jpg

Also note the call to "EnableClientValidation" method due to which client side validations are enabled.

<% Html.EnableClientValidation(); %>

Step 4:- Write your controller logic

From the UI when the form calls a post on the controller, you would like to know if the model state is proper or not. This can be done by checking the "ModelState.IsValid" property. So if this property is valid then call the save method and call the thanks view or else go back to the customer view.

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

Step 5:- Run your application to see the action

Finally run your application and see the data annotation in action.

a7.jpg
 

Summary of other data annotation attributes

There are other data annotation attributes which makes complex validation a breeze. Below are list of some of them:-

If you want to check string length, you can use "StringLength".

[StringLength(160)]
public string FirstName { get; set; }

In case you want to use regular expression, you can use "RegularExpression" attribute.

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }

If you want to check whether the numbers are in range, you can use the "Range" attribute.

[Range(10,25)]
public int Age { get; set; }

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

public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use the "Errors" collection.

var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call "TryUpdateModel" in your controller to check if the object is valid or not.

TryUpdateModel(NewCustomer);

Lab 12:- MVC 3:- Razor

Till now this article was using MVC 2 but it's high time we also start discussing and doing labs with new release versions of MVC frameworks. Change is a part of human life and same stands true for MVC as well J. So in this section let's discuss MVC 3 which was the next release version after MVC 2.

FYI: - The recent version is MVC4 and in the later days I will be touch basing even those versions. So control yourself and have patience.

In case you have not installed then click and getMVC 3 template.

a8.jpg
 

In case you are feeling that whatever we have learnt in MVC 2, is it a waste? No, not at all. On the contrary MVC 3 is backward compatible with MVC 2. So whatever you have learnt in MVC2 still holds true in MVC 3.

Now rather than discussing about all the new features let's focus on the biggest feature of MVC3 which I personally think is a game changer and that is RAZOR.

So what's Razor, just to answer short and sweet, it's a type of view for MVC. In MVC 2 the default view was ASP.NET pages i.e. Web form view. Now the problem of web form views was that it was not made thinking MVC in mind, so the syntaxes was bit heavy.

Developers demanded for a clean, light weight view and with less syntactic noise: - Answer was RAZOR.

So let's create a simple lab to demonstrate use of Razor views.

Step 1:- Install MVC 3 and create a project using the same

Install MVC 3 template and create a project selecting the MVC 3 template below.

a8.jpg
 

Step 2:- Select Razor

The next screen which pops up what kind of application you want to create.

  • The Empty option creates a project with least amount of files.
  • The Internet Application option creates a shell application which includes user registration and authentication, navigation, and a consistent visual style.
  • The Intranet Application option is very much same as Internet Application with the only difference that the authentication takes place through domain/Active Directory infrastructure.

a10.jpg
 

For now let's keep life simple and let's select the empty option. The second thing which we need to select is what kind of view we want, so let's select Razor and move ahead.

a11.jpg
 

Once the project is created you can see the Razor file with the name ".cshtml". Now the "_ViewStart" page is nothing but it's a common page which will be used by views for common things like layouting and common code.

a12.jpg
 

Step 3:- Add a view and invoke the same from controller.

Now go ahead and add a new view and invoke this view from the controller. Adding and invoking the view from controller remains same as discussed in the previous labs. Just remember to select the view as Razor view.

a13.jpg
 

public class StartController : Controller
{
//
// GET: /Start/
public ActionResult Index()
{
return View("MyView");
}
}

Step 4:- Practice Razor syntaxes

Now that we have the basic project and view ready lets run through some common razor syntaxes and try to get a feel how easy RAZOR is as compared to ASPX views.

Practice 1:- Single line code

If you want to just display a simple variable you can do something as shown below. All razor syntaxes start with @. If you have just single line of code you do not need "{". Razor figures out the ending logically.

Todays date  @DateTime.Now

If you compare the above syntax with ASPX view you need to type the below code, so isn't the syntax much simpler, neat and light weight.

<%=DateTime.Now%>

a14.jpg
 

Practice 2:- Multiple lines of code

If you have multiple line of code you can use "@" followed by "{"as shown in the below code snippet.

@{
    List obj = new List();
    obj.Add("Mumbai");
    obj.Add("Pune");
    obj.Add("Banglore");
    obj.Add("Lucknow");
}

Practice 3:- Foreach loop and IF conditions

For loops and if conditions again become simpler as shown in the below lines of code.

@foreach (string o in obj)
{
 @o
}
@if (DateTime.Now.Year.Equals(2011))
{// Some code here        
}

Practice 4:- Do not worry about @

If you are thinking will 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 he understands it's just an email address.

@DateTime.Now

Practice 5:- To display @

In case you want to display "@" just type it twice as shown in the below code snippet the display will be something as shown in the image below.

Tweet me @@Shivkoirala

a15.jpg

 

Practice 6:- HTML display with razor

In case you want to display HTML on the browser. For instance below is a simple variable called as link which has HTML code. I am displaying the variable data on the browser.

@{
var link = "<a href='http://www.questpond.com'>Click here</a>";
}
@link;

If you execute the above code you would be surprised to see that it does not display as HTML but as a simple display as shown below. Now that's not what we expect? , we were expecting a proper HTML display. This is done by razor to avoid XSS attacks (I will discuss about the same in later sections).

a16.jpg

But no worries razor team has taken care of it. You can use the "Html.Raw" to display the same as shown in the below code snippet

@{
        var link = "<a href='http://www.questpond.com'>Click here</a>";
}
@Html.Raw(link);

a17.jpg

 

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. In this lab we will try to implement windows authentication in MVC 3 application.

Now one way to implement windows authentication is by creating project using the intranet application option. As said previously intranet application option is enabled to authenticate users from windows active directory.

For now we will not use that option, let's use the empty application option and create from scratch so that we can understand better.

a18.jpg
 

Step 1:- Enable Windows Authentication

One you have create project first step is to go and enable windows authentication using the "<authentication>" and "<authentication>" tag as shown below. Yes , this code is same as we did for ASP.NET.

c3.jpg

Step 2:- Just some defects

In MVC 3 template there is a small defect. It runs the forms authentication by default. Set the below tags in appsettings tag to avoid problems. It took me 2 hours to figure this out , what a waste.

c4.jpg

Step 3:- Apply Authorize tags on your controllers / actions.

Once you have enabled windows authentication use the "[Authorize]" tag and specify which users can have access to the controllers and actions. You can also specify roles if you wish.

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
    // 
    //
    GET: /Start/  
    [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
    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.

a19.jpg
 

Step 4:- Create setup

Now it's times to go and publish this solution on IIS so that we can test if windows authentication works. In order to do the same we need to have the necessary MVC DLL's also posted to the server. So right click on the project and select "Add deployable dependencies".

a20.jpg
 

In the next screen its will prompt which dependencies you want to include. For now I have razor view so I have selected both the options.

a21.jpg
 

Once you can see the dependent DLL's been added to the project.

a22.jpg
 

Step 5:- Create IIS application

Next step is to create a IIS application with only windows authentication enabled as shown in the below figure.

a23.jpg
 

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

a24.jpg
 

Step 7:- Run the controller and action

Finally run the controller and action and see how windows authentication box pops up for userid and password.

a25.jpg
 

If credentials are entered appropriately you should be able to see the view.

a26.jpg
 

What's for Fourth day?

In the fourth day we will look in to MVC security using forms authentication and custom authentication. We will also see some more new features of MVC 3 from security point of view.

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


Similar Articles