Mvc Basics Part 3

it is time to learn a bit more so let’s see how we can build a form, add some validation and post back the user input.

If you need to revisit the concepts we covered already, here they are : Part 1, Part 2

We will continue working on the same project so you should have it open and ready :).

We will create a form which takes data for a Person and posts it back to the Controller.

So, let’s go to the TestController first and create two new actions. We will call them both Create :


The first one is the one which will display the form.

Then once the user fills in the data and presses the Submit button, they will be taken to the second one. Please note that we decorated the second Action with [HTTPPost] and we are also passing the Model as parameter. The MVC engine will take care of us in this respect.

In order to avoid any issues, at this point delete all the other actions created by default when we created the TestController. so, just keep Index and the 2 create actions and delete everything else.

Now we need to create the View :


This time we select our Model class already, we told MVC to use a scaffold template for Default so we will effectively get a functional form straight away :


You can see we already have the form and validation fields. Since we want to capture the data, it would probably be a good idea to mark the Name and Surname fields as Required.

All the basic validation can be done in our Model class. All we have to do is open the TestModels class and decorate both Name and Surname public properties with [Required].

We need to a new using line in our code to tell the system where to find the required tag : using System.ComponentModel.DataAnnotations;

Our Model will now look like this :


Please note how we told the system to not accept empty strings and also what the error message should be displayed.

So, if at this point we run the site , go to /Test/Create, not type anything and then press Submit we will see this :


Cool, huh ? 🙂

We’re not done yet. We need to write more code in our Controller to deal with the post data properly and take care of validation errors as well :


First we check that the data in the Model is valid, in our case we do have some data for both Name and Surname. At this point, we would save it to a database for example and display a simple View with a success message. We’ll leave this to you, you should be able by now we create the proper View that can do this.

If our ModelState is invalid then in typical MVC fashion we would simply redisplay the view passing in the Model. The result of this is that the form is displayed again with the correct error messages in the right place. This happens because our model would have everything it needs inside it.

So, we have seen how to create a simple form, add model validation and look at the post data inside the controller.

Let’s spice this up a little. Let’s say we now want to display a DropDownList and capture the selected value.

I chose dropdown because this one is a bit special, it requires not only the data itself but also  a separate field to capture the selected value.

Let’s edit the model to support this scenario :


Let’s update the controller as well so we have some data to send to the view :


Ok, we’re all ready, the last thing is to edit the View to display this dropdown :


If you look at the HTML Helper for DropdownList, you’ll notice that the first thing we tell it is where the post value is stored in our model and that is the SelectedGender property. Then we create a SelectList from our Gender data. There are more ways to build the dropdown and I encourage you to explore them all as they will come in handy at some point.

Now, let’s visit the Test/Create again, type some data for name and surname, choose female in the dropdown and press Submit.

The result is :


Another simple scenario is to add an email field and validation. Armed with everything you’ve learnt so far you you should be able to do this on your own. The only missing piece of the puzzle is in the model, in order to tell it that the field validation is the one required for email we will simply add a new tag [EmailAddress]. See if you can add everything you need in order to make this work.

There is another way of retrieving data from a form post. In real applications we usually have a lot more happening on a form, we could use some Jquery to populate a hidden field for example and then post that data back, or any other functionality. The point is that we do not always have the luxury of using a model to simplify our life.

So let’s see how we can have a form and postback the data WITHOUT using a model.

Let’s modify the HttpPost action so that it does not take a model as parameter anymore. Instead it will take a FormCollection object.

So our action now looks like this :


Let’s see what happens when we submit the form :


As you can see, the FormCollection object has a field for every submittable field in the form. We can peak inside these fields to see the values :


This concludes Part 3 of this tutorial.

Part 1, Part 2

Posted in Code | Tagged , , | Leave a comment

Mvc Basics Part 2

Welcome to the part 2 of this tutorial. if you need to read the first part, you can find it here : Mvc Basics Part 1

In Part 2  we will look at Models / Routes in order to get a better understanding of the MVC pattern. We will continue using the project we created in Part 1 of this tutorial.

We’re going to create a list of people that we want to display in our Test/Index view.

For this we will use a model Person.

What is a Model ? A Model is a simple representation of the data the View needs to display. It is a simple class, with public properties and maybe a constructor and no other functionality.

The purpose of a Model is not to operate on data in any way, it’s sole purpose is to prepare it for the View. Any functionality that needs to happen in order to achieve this is done in a Controller.

So, let’s start by creating our Person Model. Let’s go the Models folder and create a new class called TestModels. This is simply a convention. I’ve used the name of the Test Controller and added Models because all the models needed by the functionality in this controller will reside here. We will effectively have 1 class per model inside this container class.


Now we need to build the project so that the dll has this new class and then tell the Index view to expect this Model.

Open up the Index View inside the Views\Test folder and right at the top add this line : @model List<Mvc.Models.PersonModel>

Assuming we rebuilt the project before attempting this we should see our new Model class in Intellisense.

At this point, the Index View knows that it’s supposed to receive data in the format of a PersonModel.

Let’s populate some data and send it to the View.

Remember any data retrieval / manipulation happens inside the Controller so that’s where we will instantiate the PersonModel and send it to the view.

Open up the TestController and edit the Index action with the following code :


Please note that we changed the return statement to include our new data. This is the basic way in which we send data to a View. The object we return there must be of the same type we tell the View t expect.

Next open up the View and let’s write some Razor code to actually display this data :


Let’s look closer at this code. We used @ to tell the view that what follows is Razor code and then simply wrote some C#.

The word @Model is a generic keyword which will be of the type of the model we told the View to expect. This means that we get Intellisense on it if there are properties or items to work with. In our case @Model is a list of PersonModel and as such we can iterate over it as we would normally do and then write some basic HTML to display the data.

If we run the project now we will see the result of our work :


This concludes Part 2 of this Tutorial.

In Part 3 we will look at how we can build forms and post back some data.

Part 1 Part 3

Posted in Code | Tagged , , | Leave a comment

Mvc Basics Part 1

The purpose of this article is to explain the basics of MVC. Hopefully it will help start with this pattern, in Dot Net, should you never used it before.

What is MVC ? Mvc comes from Model View Controller. This is how the pattern works. A View is just the display of the data. The data itself comes from the Model passed to the View, and the Model gets its data from the Controller.

Let’s see how this works. For the purpose of this article i will be using Visual Studio 2012 and MVC4.

So, let’s start by creating the project :


Hit OK :


Here we select Internet Application and Razor which will be the language used in our Views.

Hit OK and we can finally see our project.


If we run it at this point we can see something working already :


Let’s go back to Visual Studio and look at the way the project is organized.

For now we have 3 folders of interest : Controllers, Models and Views where we will perform most of our work.

Let’s start with Controllers. This is where most of the functionality of our application will reside. Each Controller has a number of actions which will respond to a specific URL.

Each action method has an ActionResult result ( pardon the pun ! ). This tells the system that this action is ready to be invoked and display a View.

What kind of code can we have in a controller ? Well anything that gets the data we would like a view to display.

For now let’s start simple. Let’s create a new controller and call it TestController :


At this point we have a new controller with a bunch of default actions. What we don’t have is Views for them. It is important to understand that controllers / actions map to URLs.

So we could run the project and go to /test/index and we would expect to see something. There’s just one thing left to do create a view for the index action. So let’s go to Views folder, create a new folder called Test ( this is the name of our controller minus the “Controller bit” ). Here we create a view called Index. The engine will do the rest, by default it will look in Views/Test for a view called Index corresponding to our first action.


Now let’s run the project and go to /Test/Index


There, now we can see the new page we created. Granted, it does not do much, but hopefully the relationship between controllers / views and URLs are clear.

This concludes part 1 of this tutorial. In Part 2 we will look at Models and Routes and add some functionality to our project.

Posted in Code | Tagged , , | Leave a comment

Dependency Injection

Why is it useful and how we can implement it ?

By applying DI ( Dependency injection )  we avoid creating a hard-coded dependency in our classes.

For example, let’s consider the situation where we implement a simple logging system which logs to a text file

We would write a class called FileLogger which could look like this :

public class FileLogger
    public LogMessage(string message)
           //some logging code

We use it in our code, let’s imagine we have a class which needs to log something :

public class WorkClass
     //some properties and methods

     public WorkClass()
           //some code for this constructor

     public void DoesSomethingAndLogs()
            FileLogger fileLogger = new FileLogger();
            filelogger.LogMessage("a message");

What we have now is a class with a hard-coded dependency. Why is this bad ?

Well, let’s imagine some real life scenarios. For example, what happens if later on we want to change the logging method from file to database, or we want to unit test the code.

We need a method of being able to tell the system which logging system to use, preferably without us having to go in and modify any code. Just imagine you work on a big project with lots of classes, all of them using logging. The last thing you want is go and change all of them should you decide to log to the database for example.

In order to accomplish this, we need to change the code a little so that we achieve a clear separation of concerns.

Step 1. Code against an interface.

First we create an interface for our logging system :

public interface ILogger
      void LogMessage(string message)

Step 2. Write an implementation of this interface which writes to files :

public FileLogger : ILogger
    LogMessage(string message)
          //some code which writes the message to a text file

Step 3 Re-write our WorkClass to use the interface and use DI in the process :

public class WorkClass
     ILogger logger;
     //some otherproperties and methods

    public WorkClass(ILogger logger)
         this.logger = logger;

    public ILogger GetLogger()
        return this.logger;

     public void DoesSomethingAndLogs()
            this.logger.LogMessage("a message");

We have now used DI, the constructor takes an interface as a parameter, which could be any implementation of the ILogger interface.

The point is that now we don’t have a hard-coded dependency anymore. We can change the implementation, we can unit test it etc.

In another article we will look at how to set a specific interface implementation to be used by all our classes in the entire project.

Posted in Code | Tagged , , | 4 Comments