• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Beginning Asp.net MVC 3 And Razor With C# Code Examples

Beginning Asp.net MVC 3 And Razor With C# Code Examples

April 12, 2011 by Rana Ahsan 9 Comments

Asp.net MVC 3

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.

Create New Asp.net MVC 3 Application

* 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.

Select Template Engine And Unit Test Project

Aspn.net mvc 3 directory structure
* 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.

basic aspnet mvc 3 layout at runtime

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.

Create New Controller

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:

Running newly added page

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: .net, c#, web application

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. LeroyV says

    April 28, 2011 at 4:17 pm

    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?

    Reply
    • Rana says

      April 28, 2011 at 9:09 pm

      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.

      Reply
      • Akwin says

        November 20, 2014 at 11:46 pm

        How to create the static web page using mvc3 with razor

        Reply
  2. Pandey says

    October 12, 2011 at 3:54 am

    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 !!!

    Reply
  3. AR says

    November 11, 2011 at 11:39 am

    i didnt read the post but i got what i was looking for

    @model IEnumerable

    thumbs up

    Reply
  4. Roberto says

    August 8, 2014 at 4:29 pm

    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

    Reply
  5. Raghuram says

    September 2, 2015 at 10:22 pm

    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.

    Reply

Trackbacks

  1. Asp.net MVC 3 And Linq To SQL Based Tutorial | codesamplez.com says:
    May 10, 2011 at 10:25 pm

    […] If you are very new to asp.net mvc framework, please consider reading my previous article about getting started with asp.net mvc and razor template engine. Also, if you are new to linq, please consider reading linq to sql tutorial . We will be using […]

    Reply
  2. Apprendre MVC3 quand vous êtes expert et débutant à la fois | Blog de JP Gouigoux says:
    June 13, 2012 at 3:55 pm

    […] http://codesamplez.com/development/introduction-to-asp-net-mvc3-and-razor-in-c-sharp […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • Beginning With Facebook Graph API C#.NET
    Beginning With Facebook Graph API C#.NET
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • "Facebooksdk" - C#.NET Library For Facebook API
    "Facebooksdk" - C#.NET Library For Facebook API

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
  • Beginning With Facebook Graph API C#.NET
  • LinQ Query With Like Operator
  • "Facebooksdk" - C#.NET Library For Facebook API

Recent Tutorials

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023