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).
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".
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".
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.
Put some text or logic in partial view.
|
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.
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.
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.
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.
|
public class Customer
|
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.
|
|
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.
Also note the call to "EnableClientValidation" method due to which client side validations are enabled.
|
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.
|
Finally run your application and see the data annotation in action.
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".
public string FirstName { get; set; } |
|
|
|
|
|
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.
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.
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.
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.
|
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.
|
|
If you have multiple line of code you can use "@" followed by "{"as shown in the below code snippet.
|
For loops and if conditions again become simpler as shown in the below lines of code.
|
|
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.
|
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.
|
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.
|
|
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.
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.
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.
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.
|
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".
Next step is to create a IIS application with only windows authentication enabled as shown in the below figure.
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.
Finally run the controller and action and see how windows authentication box pops up for userid and password.
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
Are you completely new to MVC?
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 1 :- A simple Hello world ASP.NET MVC application.
Lab 2 :- In this Lab we will see how we can share data between controller and the view using view data.
Lab 3 :- In this lab we will create a simple customer model, flourish the same with some data and display the same in a view.
Lab 4 :- In this lab we will create a simple customer data entry screen with some validation on the view
Comments
Post a Comment