Download from Dropbox link.
ASP.NET has provided developers with a new framework for website development that makes it possible to easily distinguish between a data layer, a business layer and the methodology they use to render these objects on the screen. They call this framework ASP.NET MVC, in which MVC stands for Model, View, Controller. I will elaborate on these items in this article as well as other objects and technologies. I will use other things too. First let's talk about what the MVC pattern itself is and what ASP.NET MVC offers compared to other ASP.NET frameworks that include something and are well-known, such as web pages and web forms and all other web-scripting frameworks.
ASP.NET MVC
The first thing is to understand the ASP.NET MVC framework itself, once we've gotten enough understanding of the ASP.NET MVC framework, then it will be much easier us to understand why the ASP.NET team provided us with this framework. In web development, there are various schemes used to create web sites and web applications that at a minor age don't seem to cause a problem. Solving a bug might take hours of head-scratching and some other help too. It is harder to find the problem that is scripted inside the HTML web page. In these scenarios, it is always helpful to separate your code from your data and from your HTML markup. This will make it much easier to find and solve the problem. Because then all of the code has been separated and finding the problem at the exact location won't be such a hard task. These three fields are divided and make up the MVC; they are the Model, View and Controller pattern for web development.
Actually this is not a pattern, specific to the web development. If you go to the Wikipedia's web page for this, you will find that it is actually a framework used for software development, meaning that it can be applied anywhere, where you want to distinguish between your application's data link layer, business logic layer and the rendering code.
The link among these three objects of the MVC pattern have been depicted in this image above.
Controller
The Controller in the MVC comes at the last, but the most used part, of the MVC pattern. It is used to work with the HTTP requests, coming from the clients, in other words, from the browsers or from any other application that can generate an HttpRequest (not to be confused with the .NET's HttpRequest object, but a simple HTTP Request). Each request, when it comes, is handled by the Controller and then the Controller, depending on the request, makes decisions to load the data, create the response and then return the data back to the client.
It should also be noted here that your Controller acts as a bridge between your Model and the View. Because they, as themselves, cannot perform any action. The Controller triggers their events and makes them do something, like return data from a Model or to render the HTML document from the View and so on. All of the resources and errors are also handled by the Controller, making it the heart of the pattern, because the response is also sent back from a controller. You can think of an example of a Controller to be the entire Business logic layer. The code that is used to run the application's back-end processing, like creating accounts, managing solutions and so on, would make up the Controller section of this pattern.
View
Next comes the View. It is the actual web page that is being displayed to the user. It contains the HTML code to be returned to the data as a response to his request. Correct, the Controller sends this response back to the client and the View itsself doesn't send the response to the client whereas Controllers take the data and sends it back to the client.
A View can also be created dynamically. As already said, all of the requests are handled by the Controller, so any parameter (including QueryStrings) can also be handled by Controllers. Using these parameters, we can generate dynamic Views. So dynamic content in our View changes their layouts or shows some other error messages if the data sent is not of our own choice. The View generally depends on the Model that is being used to create the View and these dynamic data objects are captured from the Model (the Model is discussed in the next section).
The point to be noted here is that whereas a section-in-action is a View, still Controllers play a vital role for ing the values and for retrieving the data to be sent to client.
Model
As the name suggests, it is a model of some object. The object in this case is our application's data. It can be of any type, like extracted from a database; no matter which one, SQL Server, MySQL or Microsoft Access and so on, or it can be a simple data that comes from a Reporting, or from a Spreadsheet and so on. The Model is never shown to the user (actually, the client) because he is supposed to see the data and the results we want him to see, that is why, it is a good approach to keep a substantial abstraction layer between the Model and the user (the client).
Model doesn't only store the data, it, at the same time, keeps the View and the Controller updated of any changes made to it. Models are designed, just like Controllers and Views are designed, just so that there is no ambiguity among the three of them and it is easy for them to communicate to make the web application fluent. Every time a change is made, the View is updated by the Controller, because the Controller is informed about the change (this informing event is also raised by the Controller; as I already said, a Controller handles the events). To store anything in the Model, the user has not been provided with any form that is directly connected to the Model, instead a form is generated in the View by the Controller for the user to fill in. Once the form is filled in, the form values are then ed to the model for storing. All kinds of data validations (the most special type of which are SQL Injections) can be checked at the Controller level rather than losing (important) data.
The user must be allowed to interact with the Model himself, instead a Controller must be used to connect to the Model to get the data for the user's View that would be shown to him.
Until now, we've been discussing the ASP.NET MVC itself, in the next section we will be discussing a real-world example of an ASP.NET MVC Application and I will show showing how to create custom Controllers, Views and Models. In an ASP.NET MVC project a user triggers the Controller, the controller then reads and manipulates the requests, Requests the Model for data, gets the data and then updates the View to be sent back to the client.
Overview of MVC pattern
Real world example of ASP.NET MVC Application
In this article, I will explain the creation of an MVC application to control your client's data. For that, I will use the Model, View and Controller architecture, so that I can easily distinguish between the data of my application (that would be the data for the clients), the code for the requests and responses (that would constitute the controller) and how the data is shown to the users (the views of my application). I will create everything from scratch, to make everything understandable for you. For that I will start from creating every single object in my application, every controller, every view and model in my project.
One thing you should think about here is that I will use JSON files as the data source, because database fields have already been covered by the ASP.NET team at its best. I don't think there is any need to re-write the same thing, which is why I will explain how to use anything as your model. If you want to read that one and want to stick with SQL Server database then you can go to the ASP.NET MVC's tutorial website to learn that. You're right, Entity Framework won't be supported here! That is why I am saying I will create everything from scratch, to explain every bit of the MVC pattern for you and how you can create actions that respond to your actual processes, not just to the built-in ones.
Real-life example
Let's have an example of a simple office, where a person gets multiple clients, whose name and address are stored. Just to distinguish among them, an ID is also stored. Whether the client is trusted or not, it is also stored along with him. The office manager wants to be able to create new clients and modify the existing ones and once he is done with them he wants to be able to delete the previous ones. To implement this basic example in ASP.NET MVC, we will start off by creating a simple ASP.NET MVC application. To do so, you can either press CTRL+SHIFT+N, or you can click on File, then New and a Project ("File" -> "New" -> "Project..."). Like this:
Creating a new project - in Visual Studio 2013
After this, please select the Web and inside that select ASP.NET Web Application, then name it as you want. I named it ASPNET_MVC_Application. You can use any name you want.
Selecting an ASP.NET web application
Then you will be required to make the selections for your application in the next tab. You shouldn't make any change for now, keep the selected options selected and click Next on this tab.
This would then create your application, with the default content for your application settings. You might see this web page inside your Visual Studio.
The ASP.NET MVC read me page viewed inside the Visual Studio 2013 application's first run.
This is the tutorial until the creation of the application. This web page is also a sign of success, if you still want to be sure that everything runs, just press the Green button (with a Browser's name on it; mine had Google Chrome) to see your application run in the browser. In the next section, I will be creating the application's objects (MVC) and then showing you how they can interact and in the end I will provide some tips for making your application better.
Customizing the ASP.NET MVC Application
Once all of the things are set and your application runs, you can continue to make changes to it, so that it would reflect your own application and not the default ASP.NET MVC application that is a sample. The first thing to do is to create a controller that we're going to be using inside our application to control all of the requests and will send back the response (view). How to create views and what would be the model will be covered in future sections. For now, just make up your mind to understand the Controller in MVC.
Required package: Since we're going to use JSON data, the Newtonsoft.Json package is a very useful package to use, so before you go any further open your NuGet package manager console (inside the Tools) and run the following command to download and include it in your project. It is required.
Install-Package Newtonsoft.Json
Creating a custom ControllerA custom controller is something that you can use to create your custom controllers for your application, that would handle the requests coming for them and they will provide the user with a view filled in with the data from the model. You can name them as you would like to name them, there is no convention. There is however just the one convention that is to append “Controller” to the name of the class. Controller is a real class that inherits from the System.Web.Mvc.Controller class, making it able to inherit all of the functions and members of the Controller (parent) class. Let us create a Controller. Inside your source code, there is a folder named Controllers. If you open it, there will be 3 controllers by default, you can create your own.
Default controllers in ASP.NET MVC applicationRight-click on the Controller folder and inside the Add option, click Controller to create a new one.
Creating a new ControllerProvide a custom name to your controller. Remember to have that Controller at the end of your class's name. You must create an empty controller, because for the sake of this article we're not going to use anything built-in but instead just scratch classes.
We just need an Empty controller, to create our own functions (actions in MVC) for it to handle and perform.
At this stage, your basic Controller has been created and you're now ready to customize it. Before we move on to create actions for this Controller to perform. I wanted to remind you about (automatic) changes that were made in your Views folder. What is the Views folder about? Well it is, yes, well it is self-explanatory but we'll be talking about it too in the future section. Right now, there is a new Client (or whatever Controller you created is named) folder inside your View folder. Now it is beginning to make some sense, isn't it? Every controller has its own specific view to display data for, and each time the request will be initiated from the client (not our class, but the user of course). The Controller would be used (you can think that an instance of that class would be created) and then the Action of Controller would be checked against (inside the URL that would then trigger the function of the Controller that we're going to create next). Like every class, we can create multiple functions for our Controllers that are known as Actions. Let us think what we're supposed to let our manager do with the client, he wants to:
- Create a new client: Create
- Modify the current client's data: Update or Edit
- Delete clients when he has finished the work: Delete
We can use the preceding logic to create our functions for the Client Controller. Open your ClientController.cs file and edit it, to write this code in it.
Done! That was our controller, if you have a look at the code above you will find a few functions, a few ViewBags and a few Views and so on. I will explain them in the end, because they're built-in functions of ASP.NET MVC for the application and that we are bound (required) to use them for the application to run. Each time you're going to create a request to your application to load data about clients, this controller would take action and will provide the data that the user (in this case, you) want from the application. In the preceding code, Create, Update, Delete and Index are the functions of the class. In the MVC application they will act as Actions of the application's Controller. You will use them to tell the application what to do, when the user triggers such a specific action in your application. They're just average functions in a simple class that inherits from System.Web.Mvc.Controller.
Creating a custom ViewNow that the back-end (Controller) code has been done you can now create the Views for your application. Views are used to show the content (data) of your application to the client (user) in HTML markup. Because a browser can only render HTML content, we will be using that markup and Views are used for that. Each controller has its own specific view. One thing to note here is that to return a View, the name of the View must match the Action's name. You can say that each of the Actions (functions) in the Controller is meant for a specific View (HTML document to be returned) in the application. We need four Views, for our four Actions, Index, Create, Update and Delete. To create a View you can click on the the Views folder and create a new folder. Remember, however, that here you don't need to create a new folder, because as I already said, when you created the Controller a new folder was already created with the name of the Controller, “Client”. Right-click that folder and inside the Add click on the MVC 5 View with Layout and click Next to go to the next step.
Creating a new View (with Layout)Now name the View, I named it Index because we need a view for the Index page.
Now select the layout. The layout is applied across the pages (Views) to design them alike. You can use your own views too, but for this I will use the default layout.
This is the step-by-step method to create the View in ASP.NET MVC using Visual Studio. ASP.NET uses Razor syntax to create HTML pages that shortens the code for developers. Update the code inside this page and write the following code:
- @model IEnumerable<ASPNET_MVC_Application.Models.Client>
-
- @{
- ViewBag.Title = "All Clients";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h3>Following table shows the Clients detail</h3>
- <p>You will find their details, as well as other links to other actions that can be performed and operated over the client objects. </p>
-
- <p>You can also create a new client <a href="~/Client/Create">here</a>. </p>
-
- <table class="clients-table">
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Address</th>
- <th>Trusted</th>
- <th>Actions</th>
- </tr>
-
- @if(Model != null && Model.Count() > 0)
- {
- foreach (var client in Model)
- {
-
- <tr>
- <td>@client.ID</td>
- <td>@client.Name</td>
- <td>@client.Address</td>
- <td>@client.Trusted</td>
- <td>
- <a href="~/Client/Update/@client.ID">Update</a>
- <a href="~/Client/Delete/@client.ID">Delete</a>
- </td>
- </tr>
- }
- }
- </table>
In the preceding page's source code, you will find the following:
@model IEnumerable<ASPNET_MVC_Application.Models.Client>
That is the type of the data that must be used inside this View; yes, it is the model being used here. After that it is just simple Razor syntax, to create the HTML document (View) and return it to the client (user). The Model object (the one used in the foreach loop) has the value of whatever is ed for the @model thing.
You should create the next three Views yourself (as a test) and write this content to them.
To create the View:
- @{
- ViewBag.Title = "Create";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <div>
- <h3>Fill in the following form</h3>
- </div>
- <form method="post" style="margin: 5% 0 0">
- <div class="float-left">
- <p>Client ID</p>
- <p>Name</p>
- <p>Address</p>
- <p>Trusted</p>
- </div>
- <div class="float-right">
- <input type="text" style="margin: 1px 0 2px" name="id" /><br />
- <input type="text" style="margin: 1px 0 2px" name="name" /><br />
- <input type="text" style="margin: 1px 0 2px" name="address" /><br />
- <input type="checkbox" style="margin: 1px 0 2px" name="trusted" /><br />
- <input type="submit" value="Save" />
- </div>
- </form>
-
- <p>
- @if (ViewBag.Submitted)
- {
- // If the form was submitted
- @ViewBag.Message
- }
- </p>
To update the View:
- @model ASP.NET_MVC_Application.Models.Client
-
- @{
- ViewBag.Title = "Update the Client";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
-
- <div>
- <h3>Update the following form</h3>
- </div>
- <form method="post" style="margin: 5% 0 0">
- <div class="float-left">
- <p>Name</p>
- <p>Address</p>
- <p>Trusted</p>
- </div>
- <div class="float-right">
- <input type="text" style="margin: 1px 0 2px" name="name" value="@Model.Name" /><br />
- <input type="text" style="margin: 1px 0 2px" name="address" value="@Model.Address" /><br />
- <input type="checkbox" style="margin: 1px 0 2px" name="trusted"
- @if (Model.Trusted) { <text>checked="checked"</text> }
- />
To delete the View:
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <p>@ViewBag.Message</p>
You will find that in the Create view I am not ing a model. That is because, for a View, a model is optional. The Model is just to allow dynamic content for it. If you don't want to use a model then fair enough, you don't have to use a model in every view to create an MVC application. These are just simple HTML pages that are being made to update-to-the-content by the razor syntax and then sent back to the browser in an HTML markup, for rendering purposes. The _ViewStart.cshtml page is used as the first page to check for any layouts. If you don't want to set any layout for all of the pages themselves and want a unique look across the web app, you can set that in this page and it will be applied to all of the pages.
Creating the custom ModelAs far as Model is concerned, ASP.NET MVC allows you to use any kind of data (coming from a data source, server or whatever) to be used as a Model. You can the data from the model to the view from the Controller that will be then rendered as a simple HTML markup and will be displayed inside the browser to the user.
I have already said, and if you missed it above, I will say again, if you want to use a SQL Server database as your Model for an application then the ASP.NET team has provided a very good tutorial for that and you might want to join them on their journey
here. They used Entity Framework for their Actions. In our project, we will be using JSON files and custom Actions to do CRUD operations. This would (try to) remove ambiguity in our minds about this MVC pattern and its extensiveness for other technologies and frameworks.
A Model, like a Controller, is just a class file, that we can instantiate and get multiple objects from, when working with a request from a client. A model is a representation of the real-world objects in our own context that here is the ASP.NET MVC Application. Think of it like there is a Client model. He would have a ClientID, Name, Address and a Trusted as a flag (you should recall our scenario if you have no idea of where these came from). What would you write as a class for this Client? Look at the following class code and get an understanding of the Model we're going to have.
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- using Newtonsoft.Json;
-
- namespace ASP.NET_MVC_Application.Models
- {
- public class Client
- {
- public static string ClientFile = HttpContext.Current.Server.MapPath("~/App_Data/Clients.json");
-
- public int ID { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public bool Trusted { get; set; }
-
- public static List<Client> GetClients()
- {
- List<Client> clients = new List<Client>();
- if (File.Exists(ClientFile))
- {
-
- string content = File.ReadAllText(ClientFile);
-
- clients = JsonConvert.DeserializeObject<List<Client>>(content);
-
-
- return clients;
- }
- else
- {
-
- File.Create(ClientFile).Close();
-
-
- File.WriteAllText(ClientFile, "[]");
-
-
- GetClients();
- }
-
- return clients;
- }
- }
- }
That is a simple C# class file that would serve our application as a Model. You will find that one other major change is the namespace this class is in. The name has an extra .Models attached to our project's name. That makes up our different fields. ASP.NET and Visual Studio do these things for us, although they're not required but just conventions to be followed. Let us create a Model for our application, click on the Models folder in your app and inside Add click on the Class file and name it Client.cs and click Next to continue.
Select a new class file to be created as a Model
Name it whatever you want, but I am using Client.These were the three major fields in the MVC that are used to create an application. However, there are a few other minor fields that work and run our application, that I will be covered here for you to at least understand how to kick-start your project.
So far, we have covered what the Controller is (it controls the HTTP requests coming from or going to the client), what a View is (it is rendered as HTML output in the browser, the response that is returned to the client in HTML markup can be said to be the View) and finally what a Model is (the representation of the real-world data in our application is called a model). Now, we can go and have a look at the classes and objects that run our application. Like all other apps that run using the .NET framework, ASP.NET also exposes some functions for its developers to use, to perform various actions when the app starts, when the app crashes and so on. If you open the folder App_Start in your application, you will find a few classes there. BundleConfig configures your JavaScript libraries, ASP.NET also enables the developers to do some client-side actions. IdentityConfig configures the Identity service (user authorization servicer), but the main file that I wanted to talk about here that needs our attention too, is the RouteConfig.cs file.
In ASP.NET, you do not need to have a physical path fixed in order for the client to send a request to its virtual location to read it. Instead, you can now create custom URLs to let your users visit your application, without you having to have a specified file at that location. You create multiple routing techniques, to allow different data values inside the URL to create dynamic web pages for the clients.
If you open up this file, you will find the following code in it (I will use a partial part of the file):
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
This defines a route for your application. It has been named “Default” and has the default configurations for the URL, any URL that comes will be matches against this scheme. The first value would match for a Controller second to an action (the function inside the Controller class) and then an optional field (see the default values field). You can change this sequence of arrangement, to ensure that the URLs are websites and user-friendly for your context.
Every ASP.NET can have many routes enabled in it, all will be used except the best possible route would be chosen. At least one route however must be present for the app to run. Let us now run the app and test for anything that might need our attention.
Running the application (Optional part; if you want to download and test the app, skip this section)This application was run over the app named “ASP.NET MVC Application” but I created a new app named “ASPNET_MVC_Application”, there is a huge difference between these two, usually only difference is the namespace naming one so if you were following the article you might find this a bit confusing, so my apologies for that. :)
In the beginning, the table is empty.
Now let us start adding a few objects. For this instance, let us just take one object under consideration.
Fill in this form and click Save, the application will save this client's information.
A message shows the success of our operation.
If you return to the main page of the Client's directory (controller), you will find a record available there.
Let us now try to update this client's value. In the Actions attribute of the table, you will find two hyperlinks, they actually are just Actions (functions) of our controller, we will an (optional) ID of our client to it and then we will update the value. We will update our value as in the following:
Let's go back and see if our View now reflects any change.
Voila! It does reflect our change. That proves that a Model updates the View for any new change that we make. Try using the second hyperlink, it will delete the object from the collection.
That was up, for the working process. Now our application runs well enough, our manager can add clients, remove clients or modify their data depending on his requirements. As far as I now, this application is running and our clients can visit and use it depending on their requirements.
This was a basic overview of an ASP.NET MVC application that contains the Model for our data and a View for the users to visit and see and a Controller that controls the HTTP data coming or going to the client.
Points of InterestThe ASP.NET MVC pattern contains a Controller for controlling all of the HTTP requests received and the responses being returned to the clients. A view for generating HTML web pages, the Razor view engine is used for creating the HTML markup from C# objects. A Model is a simple C# class that contains the object's properties. Each time the application is run, the Controller gets the data from the Model and populates the View for the user to read the result in his/her browser.
Every real-world object can be used in an ASP.NET MVC application as the data source. To create a model, C# files are used (if you're using C#, otherwise you would be creating a file related to your language). The properties and members act as properties that you would be using inside your HTML markup for rendering purposes.
You can control what kind of URLs are being used in your application by creating routing techniques. These define the structure of your application's URLs. You must define at least one route in your application for it to run, otherwise you can define as many as you want.
The MVC pattern removes the ambiguity between the data and the code-behind of your application. Your code-behind is now a part of the Controller of your application and is written inside the Controllers. The data is stored inside the Model (actually that is just the representation of the data, the actual data is stored in somewhere like a file or database) and what user sees is written in the View. This way, any error can be fixed as soon as possible without having to worry about any other bug, because every field is now controlled and written in a different part.
The Model part of this pattern must never perform any kind of business-logic, because that would entirely kill the actual purpose of this MVC pattern. That is why, all of the logic code is written in the controller, even the creation of data or the manipulation of data should be done in the controller using functions, since the user has no connection with the Model, it provides an extra layer of safety since the user is totally oblivious to the schema of the database.
ViewBag and the View are special objects in ASP.NET used to manipulate the View (HTML markup), you can any member (that is dynamic) to this ViewBag from the Controller, to be used inside the View page (.cshtml in these cases) for rendering, as I did for showing some messages like an error or a success message.