
The MVC(Model/View/Controller) design pattern became a very popular and reliable software development methodology. To apply this effectively on web applications, microsoft released new framework based on mvc pattern for web application developments, named Asp.NET MVC. The latest version of asp.net mvc is 3.0. In the way, there was a lot of improvements. Now, its 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 am assuming, you know what is mvc. If you don’t , please start with reading through wiki article on mvc. To complete this tutorial, 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 is a number of view engines are supported by asp.net mvc 3.0. You can choose anyone of them. They are Razor, Spark, NHaml and NDjango.
- Global Action Filters: To execute some predefined functionality either before or after a controller function is execute, mvc 2 introduced ‘action filters’. However, it only worked for function level, like, if you want to execute something before every controller method, you would have to add the filter on each method. Asp.NET MVC 3.0 improved it and introduce ‘Global Action Filters’, which will work for all controller functions. We can say this as class level filters also.
- “ViewBag” Property For Views: Besides ViewData properties, now asp.net MVC 3 have another property named ‘ViewBag’. This provides a simpler way to access data in view. Such as, in ViewData, we had to use ‘View[“mydata”] = user;’ type syntax(utilizing Dictionary). On ViewBag, we can use ‘ViewBag.user = user;’ and can be used as a dynamic variable in view templates.
- JSON Binding Support: Asp.net MVC 3 supports json data binding with controller action method which links to client template data.
Walk-through 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 basic asp.net website before, you may know, just changing the source code makes your site updated(if you are hosting direct code instead of complied one), its recompiled when run. In case of asp.net mvc application, this won’t work. You will have to rebuild the application every time you make changes and then update the dlls to your site.
* On the next window, you will get options for selecting whether you want a empty application or some basic code integrated application(option ‘Internet Application’). As a beginner, 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 base. Besides, you will get option for choosing your template engine, select ‘razor‘. Also, if you are interested to use unit testing(recommended), select the ‘create unit test project’ check-box.
* Now look at the directory structures of the newly created application. You will find three main directories(‘Models’,’Views’ and ‘Controllers’) there, which contains their corresponding files. Beside, there is a directory named ‘Scripts’, which contains some already added javascript libraries(including jquery) and a directory named ‘Contents’, which may contains style sheets and other static files. And sure, you can add other directories also. However, its recommended that, if you are going to use something big to be integrated here, better to do those tasks on a separate project and add their references on this project.
* Run the application, you will find a basic layout with home/about/login/register pages. Play around a while around those files to have a basic idea at a glance. For ‘home’ and ‘about us’ page, home controller processes the requests and these page don’t have any model associated with them. For register and login page, Account controller does the work, ‘AccountModels’ model contains the data access logic of these pages. We are not going to discuss on them on this tutorial.
Create A new page along with its associated model,view and controller:
Lets start with creating a model class. Just 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; } } }
As you can see some attributes like ‘Required’,’DataType’,’Display’ etc for each field, the defines the strategy of model bindings with views, but i won’t go with these further(hope to post another tutorial for details on them, keep in touch 🙂 ).
Now, lets create a controller class. right click the ‘Controllers’ directory, go to the ‘Add->Controller’ option, name your controller as ‘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 add/edit/delete etc. You will notice that, there is two different method for each ‘Create’, ‘Edit’ and ‘Delete’. One for view the template page only, second one(with ‘HttpPost’ attribute) for process the posted data after user submits. For now, lets edit the ‘Index’ method, which is executed by default when this controller are requested via ‘http://localhost:5000/Blog’ url.
Here is the code snippet for this method, with which we wants 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); }
Now, lets 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, select ‘Add view’ option.Keep the default name ‘Index’, select the view engine ‘Razor’. Check the check-box ‘Create a strongly typed view’, select the class ‘ArticleModel’ from the list of model classes(remember, you will may 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 several codes has been automatically generated on our new view, which actually has all the basic action links and structure that we may need.
Now can run the application again to see what 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 write any code for template and therefore you may not understand yet how ‘razor’ works. But, hope you will get a very good 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>
you can see, the code element of razor engine is the ‘@’ character. as long as you write this one, you can use other view elements with as usual visual studio intelligence. you can also use the .net variables, for/foreach loops, if conditions etc basic features as well. So, adapting this new template engine, not hard at all, rather easy to use than general asp.net approach.
References:
To move furthur 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 of, including video tutorials.
- Blog article
- Razor on codeplex
Happy coding 🙂
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?
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.
How to create the static web page using mvc3 with razor
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 !!!
i didnt read the post but i got what i was looking for
@model IEnumerable
thumbs up
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
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.