Lab 10: Partial views

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

Reusable views can be achieved by creating “Partial views”.

Step 1: Create a simple view

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

In case you are coming to this section directly, please see the previous Labs to synch up.

Step 2: Create a simple partial view

Now that we have created the main view, it’s time to create a partial view which can be consumed inside the “Index” view. In order to create a partial view,
right click on the view folder and mark the check box “Create a partial view” as shown in the below figure.

Step 3: Put something in the partial view

Put some text or logic in your partial view.

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

Step 4: Call the partial view in the main

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

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

Also ensure that the partial view is in the same folder where your main view is. In case it’s not,
then you need to also pass the path in the RenderPartial function.
You can see in the below figure I have moved the partial view in the main “Views” folder.

One more thing which is noticeable is that the icons for main view and partial are very different. You can see the yellow border in the partial view icon which
does not exist in the main view icon.

Step 5: Run the program and see the action

Finally do a CTRL + F5, put the proper controller path, and see your results. Below is the snapshot of how things should look like.

Lab 11: Validation using Data Annotation

Validating data is one of the key things in any web application. As a developer you would like to run validation both on the client side (browser) and on the server side. So you would probably like to write the validation once and then expect the validation framework to generate the validation logic on both ends. Good news, this is possible by using data annotations. In MVC you validate model values. So once the data comes inside the model you would like to question the model saying, is the data provided proper?
Are values in range? etc.

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

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

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

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

Step 1: Decorate model with data annotation

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

using System.ComponentModel.DataAnnotations;

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

Step 2: Change the ASPX code

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

<%= Html.ValidationSummary() %>

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

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.

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

<% Html.EnableClientValidation(); %>

Step 4: Write your controller logic

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

Lab 12: MVC 3: Razor

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

FYI: The recent version is MVC4 and in later days I will touch base even those versions. So have patience.

In case you have not installed this, then click and get MVC 3 template.

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

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

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

Developers demanded for a clean, lightweight view and with less syntactic noise:
The answer is Razor.

Step 2: Select Razor

The Internet Application option creates a shell application which includes user registration and authentication, navigation, and a consistent visual style.

The Intranet Application option is very much the same as Internet Application with the only difference that the authentication takes place through
a domain/Active Directory infrastructure.

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.

Step 4: Practice Razor syntaxes

Now that we have the basic project and view ready, let's run through some common
Razor syntaxes and try to get a feel of how easy Razor is as compared to ASPX views.

Practice 1: Single line code

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

Todays date @DateTime.Now

If you compare the above syntax with an ASPX view, you need to type the below code.
So isn’t the syntax much simpler, neat, and lightweight?

<%=DateTime.Now%>

Practice 2: Multiple lines of code

If you have multiples line of code you can use “@” followed by “{“as shown in the below code snippet.

Practice 3: Foreach loop and IF conditions

Practice 4: Do not worry about @

If you are thinking if Razor confuse with @ of Razor and @ of your email address, do not worry,
Razor understands the difference. For instance in the below line,
the first line Razor will execute as a code and the second line of code it understands is just an email address.

@DateTime.Now
questpond@yahoo.com

Practice 5: To display @

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

Tweet me @@Shivkoirala

Practice 6: HTML display with Razor

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

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.

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

Now, one way to implement Windows authentication is by creating a project using the
Intranet Application option. As said previously, the Intranet Application option
is enabled to authenticate users from the Windows Active Directory.

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

Step 1: Enable Windows authentication

One you have created a project the first step is to enable Windows authentication using the tag shown below.
Yes, this code is the same as we did for ASP.NET.

Please note the user should be present in your Windows AD or local user group. Like in my case Administrator is present in my local
Windows user group.

Step 4: Create setup

Now it’s time to go and publish this solution on IIS so that we can test if Windows authentication works. In order to do the same we need to have the necessary MVC DLLs also
posted to the server. So right click on the project and select “Add deployable dependencies”.

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

Once you can see the dependent DLLs been added to the project.

Step 5: Create IIS application

The next step is to create an IIS application with only Windows authentication enabled as shown in the below figure.

Step 6: Publish

Once you have created the IIS application, it’s time to publish your application to the web application folder. So click on
Build and Publish as shown in the below figure.
I have used “File system” as the publish method, you can use your own choice.

Step 7: Run the controller and action

Finally run the controller and action and see how the Windows authentication box pops up for user
ID and password.

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

Lab 14:- MVC Security (Forms Authentication)

In the previous lab we saw how to do windows authentication. Windows authentication is great for intranet websites. But as soon as we talk about internet websites, creating and validating users from Windows ADS / work groups is not a feasible option. So in those kind of scenarios “Forms authentication” is the way to go.

Step 1:- Define the Login page controller

The first thing we need to do is define the controller which will invoke the login view. So I have created a simple index action which invokes a view called as Index. This index view will take inputs like username and password.

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

Step 2:- Create the index view

The next step is to create the login form which will take username and password. To create the form I have used razor view and the HTML helper classes. In case you are new to HTML helper classes please see Day 1 lab.

This HTML form is making a post to the action “Login” which is currently in “Home” controller and its using HTTP POST method. So when the user presses submit, it will hit the “Login” action. The next thing after this is to create the “Login” action which will validate the username and password.

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.

@{ Layout = null;}<!DOCTYPEhtml><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.

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.

By professional I am a Corporate Trainer.
I do trainings on WCF, MVC, Business Intelligence, Design Patterns, HTML 5, jQuery, JSON and many more Microsoft and non-Micrsoft technologiees.
Find my profile here

One should take a low mark as a challenge to improve, rather than an insult to defend.

I have given your previous articles that are part of this series marks of 5, however this particular article does not reach the same level of construction as the others. The title of your series, "Learn MVC (Model view controller) Step by Step in 7days" is an obvious indication that you, as the author, would include each step needed to achieve the goals of each Lab. If a user is unable to complete the Lab given your instructions are incomplete, it causes adverse effects on the expectation of the user, which is to Learn MVC, step by step, in 7 days.

It is also obvious that understanding all points of the MVC design pattern will not be achieved without a great deal of experience. This is why I so much appreciate this very intuitive tutorial.

So please, take my mark of 2 not as a slam against your work and willingness to share,nor is does it reflect my opinion of your quality of work, but it is simply a mark to indicate the level of clarity I receive with this article, on a scale of 1-5. I am simply unable to complete this lab because it appears to have missing information. Others users have stated the same in this and other posts within your series. In lieu of this, I understand not one person can cover all of the misconceptions and misunderstandings of another. That said, please know that I will continue to refer to your article as a viable resource for MVC design pattern.

First off, I would like to thank you for a very helpful post that you have here. Being a newbie to ASP.NET, MVC and C#, I have to take serious study but I was relieved that you offered a great article to help me.

Well, my concern is really about connecting my application to a MySQL database so I could display the data from my MySQL table as well as manipulate the data. I have found several articles online regarding the topic but I find them really hard for me to understand. I really appreciate you explaining everything in your article and that is what is lacking in the articles I found.I hope you could help me with my learning.

I followed first and second part and this third one bit a more confusing to me.
As i can see there's two ways done in a data annotation
one is using aspx one and second one using razor one i would like to see the validations more to put the things on a cshtml
Any ways its nice

Sorry guys i know how much you want to see this series completed. I am trying to squeeze time from my hectic and personal schedule. Above is day 4 and i promise to complete this series as soon as possible.

I think the author is not willing to provide rest session for day 4 to 7. He can make it clear that for further session have to buy book or something else. These three session has been posted year back. Still people waiting for next session.