The MVC(Model/View/Controller) design pattern became a very popular and reliable software development methodology. To apply this effectively to web applications, Microsoft released a new framework based on the MVC design pattern for web application developments, named Asp.NET MVC. The latest version of asp.net mvc is 3.0. On the way, there were a lot of improvements. Now, it is a very robust web application framework to work with. Today, in this tutorial, my goal is to make you familiar with Asp.NET MVC 3, and walk through a basic hello world application along with the introduction to asp.net template engine ‘razor’. I assume you know what MVC is. If you don’t, please start by reading through the wiki article on MVC. To complete this tutorial, the recommended prerequisites are as follows:
- Visual Studio 2010
- Asp.NET MVC 3(Properly installed on Visual Studio).If not, please install it from here, http://www.asp.net/mvc/mvc3
Improvement And Features Overview On Asp.Net MVC 3.0:
- Support for Multiple View Engines. There are a number of view engines supported by asp.net MVC 3.0. You can choose any one of them. They are Razor, Spark, NHaml and NDjango.
- Global Action Filters: MVC 2 introduced ‘action filters’ to execute some predefined functionality either before or after a controller function is executed. However, it only worked at the function level. For example, if you want to execute something before every controller method, you would have to add a filter to each method. Asp.NET MVC 3.0 improved this and introduced ‘Global Action Filters’, which will work for all controller functions. We can also say this as class-level filters.
- “ViewBag” Property For Views: In addition to ViewData properties, asp.net MVC 3 now has another property named ‘ViewBag’. This provides a simpler way to access data in view. For example, in ViewData, we had to use ‘View[“my data”] = user;’ type syntax(utilizing Dictionary). On ViewBag, we can use ‘ViewBag.user = user;’, which can be used as a dynamic variable in view templates.
- JSON Binding Support: Asp.net MVC 3 supports JSON data binding with a controller action method that links to client template data.
Walk-through of a Basic Asp.NET MVC 3 Application:
* On your visual studio, please go to File->New->Project; On Visual c#->Web Section, you will see the option to create ‘Asp.net MVC 3’ application. Select that, set your other preferences(project name, project directory) and click ok. Remember, don’t go with option ‘File->New->Website’, that is for basic asp.net website, not for mvc website, this one is treated as ‘web application’ rather than ‘website’. Also, if you were using a basic ASP.net website before, you may know that just changing the source code updates your site (if you are hosting direct code instead of a compiled one), and it’s recompiled when run. In the case of the asp.net MVC application, this won’t work. You will have to rebuild the application every time you make changes and then update the .dll files to your site.
* In the next window, you will get options to select whether you want an empty application or some basic code-integrated application(option ‘Internet Application’). As a beginner, the better choice is to get the template application, as that will help you a lot in the way of learning by checking out those code bases. Besides, you will get option for choosing your template engine, select ‘razor’. Also, if you are interested in using unit testing(recommended), select the ‘create unit test project’ checkbox.
* Now look at the directory structures of the newly created application. You will find three main directories(‘Models’,’Views’ and ‘Controllers’) there, which contain their corresponding files. Besides, there is a directory named ‘Scripts’, which contains some already added javascript libraries(including jQuery) and a directory named ‘Contents’, which may contain style sheets and other static files. And sure, you can add other directories also. However, it is recommended that if you are going to use something big to be integrated here, it is better to do those tasks on a separate project and add their references to this project.
* Run the application; you will find a basic layout with home/about/login/register pages. Play around a while with those files to get a basic idea at a glance. For the ‘home’ and ‘about us’ pages, the home controller processes the requests, and these pages don’t have any model associated with them. For the register and login page, the Account controller does the work, and the ‘AccountModels’ model contains the data access logic of these pages. We are not going to discuss them in this tutorial.
Create A new page along with its associated model, view and controller:
Let’s start with creating a model class. To keep this tutorial simple, we won’t do any database operation here. In the ‘models,’ add a new class file and name it ‘BlogControllers.cs’. Following is the code snippet for this file, which defines a class named ‘ArticleClass’:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class ArticlesModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Description")]
public string Description { get; set; }
}
}
Code language: JavaScript (javascript)
As you can see, some attributes like ‘Required’,’DataType’,’Display’, etc., for each field define the strategy of model bindings with views, but I won’t go with these further(I hope to post another tutorial for details on them; keep in touch 🙂 ).
Now, let’s create a controller class. Right-click the ‘Controllers’ directory, go to the ‘Add->Controller’ option, name your controller ‘BlogController’, and click ‘Add’. You can have some predefined methods added to your controller class, like ‘create’/’delete’/’edit’ and ‘details’. To get them, check the box beneath the controller name input box.
In the newly created file, you can see all the methods for adding/editing/deleting, etc. You will notice that there are two different methods for each ‘Create’, ‘Edit’, and ‘Delete’: one for viewing the template page only and the second (with the ‘HttpPost’ attribute) for processing the posted data after the user submits it. For now, let’s edit the ‘Index’ method, which is executed by default when this controller is requested via the ‘http://localhost:5000/Blog’ URL.
Here is the code snippet for this method, with which we want to show the list of articles:
public ActionResult Index()
{
List<ArticlesModel> articles = new List<ArticlesModel>();
ArticlesModel article1 = new ArticlesModel();
article1.Title = "First Blog";
article1.Description = "Description For First Blog";
articles.Add(article1);
ArticlesModel article2 = new ArticlesModel();
article2.Title = "Second Blog";
article2.Description = "Description For Second Blog";
articles.Add(article2);
return View(articles);
}
Code language: PHP (php)
Now, let’s add a view page. You can either add this manually by creating a new view file in the view directory or right from the controller file(simplest and recommended). Put your mouse cursor inside the ‘Index’ method, right-click, and select the ‘Add view’ option. Keep the default name ‘Index,’ and select the view engine ‘Razor.’ Check the checkbox ‘Create a strongly typed view,’ and choose the class ‘ArticleModel’ from the list of model classes(remember, you will need to rebuild the project before you can see the newly added model in this list). Select a scaffold template named ‘List’. Click ‘Add’. You will see several codes have been automatically generated on our new view, which actually has all the basic action links and structure that we may need.
Now, you can rerun the application to see what you have just created. On the URL ‘http://localhost:5000/Blog’, we will see a page like the following image:
Introduction to razor template engine:
We haven’t written any code for the template, and therefore, you may not understand how ‘razor’ works yet. But I hope you will get an excellent idea by looking into the code snippets on our newly created razor template. Here is the code of that template:
@model IEnumerable<MvcApplication1.Models.ArticlesModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
Title
</th>
<th>
Description
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
@item.Title
</td>
<td>
@item.Description
</td>
</tr>
}
</table>
Code language: HTML, XML (xml)
You can see that the code element of the razor engine is the ‘@’ character. As long as you write this one, you can use other view elements with the usual visual studio intelligence. You can also use the .net variables for/for each loop, if conditions, etc., and primary features. So, adapting this new template engine is not hard at all but rather easier to use than the general asp.net approach.
References:
To move further on and know more details on asp.net MVC, you will may like to refer to the following resources as well:
- Official Asp.net MVC site has a bunch of tutorials to start off, including video tutorials.
- Blog article
- Razor on codeplex
Happy coding 🙂
LeroyV says
For some reason, my project is not aware of the models and they don’t show up in the dropdown when I’m creating a view…
Any ideas why? I followed your tutorial step-for-step (twice), yet it is still not correct. You also have an error in your blog content: “In the ‘models’ add a new class file and name it ‘BlogControllers.cs’.”
Don’t you mean ArticlesModel.cs?
Rana says
Yes, Thanks for bring it to my attention, I just fixed it. It will be ‘ArticlesModel.cs’ . About your issue, i once mentioned that, after adding the model, you will have to rebuild the project successfully before you can see that model on the ‘model classes’ list. Did you do that? Also, your model classes need to be with public identifier to be accessible.
Akwin says
How to create the static web page using mvc3 with razor
Pandey says
Hello,
this is great stuff !!! thanks for sharing with us.
@LeroyV, please check the following url it might be useful for you.
http://www.mindstick.com/Articles/9efe98dc-b580-451a-a20e-16bb3e8438ce/?MVC%20Application%20using%20Razor%20View
Thanks !!!
AR says
i didnt read the post but i got what i was looking for
@model IEnumerable
thumbs up
Roberto says
i’m having a problem with the last step, i create the view without any problem, but when i rebuild i see the same view than before, not the new one and i’ve done everything step by step without errors
Raghuram says
When I type
List articles = new List();
after creating controller
An error “The type or namespace name ‘ArticlesModel’ could not be found appeared.
Please guide me.
I have already created ArticlesModel class in model as explained.
Controller created after rebuilding project.
I have created controller with empty read write.