Click here to Skip to main content
15,867,990 members
Articles / Web Development / ASP.NET

Basics of ASP.NET MVC3 (Part-I)

Rate me:
Please Sign up or sign in to vote.
4.46/5 (10 votes)
22 Mar 2012CPOL4 min read 95.2K   3.6K   57   13
Explains basic information and steps for creating an MVC3 application.

About This

This article explains the basics of MVC 3, the Razor view engine functionality, and custom helper class creation.

Introduction

I assume readers have a basic knowledge of the MVC pattern (if not please find the reference links for details of MVC). Therefore I am not explaining the basics of MVC and the MVC 1, 2 features. MVC 3 has a lot of new features and improved functionality. This article will explain the basic concepts of the Razor view engine with a simple MVC3 application.

Prerequisites

  1. VS 2010
  2. MVC 3 framework

Overview of the MVC3 Demo Application

This article explains a simple MVC3 application with the Razor view engine. This application shows a list of all available products and selected product details in a web page. This application is named MVC3Demo.

Image 1

Creating an MVC 3 application

Step 1

LanguageVisual C# or Visual Basic
Target Framework.NET Framework 4
Installed TemplatesWeb
TemplateASP.NET MVC 3 Web Application
NameMVC3Demo

Image 2

Step 2

After clicking the OK button in the New Project window, the MVC 3 project templates window will open.

Image 3

Select the Template section which has three application templates:

  1. Empty
  2. It creates an empty MVC 3 project without Controller and View pages. But it will create CSS, JavaScript (jQuery) files and Master layout pages with an empty template.

  3. Internet Application
  4. It creates AccountController, HomeController and related views with code for running with Forms authentication.

  5. Intranet Application
  6. Similar to Internet Application, it creates basic controller and related code with Windows authentication.

Please select Empty Template and the view engine as Razor; there is one more view engine ASPX (similar to the previous MVC version).

Step 3

The Empty template has some basic folder structure and default files. See the screenshot for the default files when choosing the Empty template.

Image 4

Note: The Razor view engine creates a view file extension with CSHTML for C# and VBHTML for VB.

Creating the Model

Right click the Models folder and create a class file ProductModel.cs and add some properties. In this example, I have created PrdCode, Name, and Price as properties and GetAProduct and GetAllProduct as methods.

C#
public class ProductModel
{
    [DisplayName("Product Code")]
    public int PrdCode { get; set; }
    [DisplayName("Title")]
    public String Name { get; set; }
    [DisplayName("Price in $")]
    public double Price { get; set; }

    private IList<productmodel> PRODUCTS
    {
        get
        {
            IList<ProductModel> prs = new List<ProductModel>() 
        { 
            new ProductModel()  { PrdCode =100001, Name ="Baby Product 1", Price =10},
            ...
            ...
            ...
           new ProductModel()  { PrdCode =100020, Name ="Baby Product 20", Price =30}   
        };

            return prs;
        }
    }

    public ProductModel GetAProduct(int prdCode)
    {
        ProductModel prd = PRODUCTS.Where(x => x.PrdCode == prdCode).Single<ProductModel>();

        return prd;
    }

    public IList<ProductModel> GetAllProducts()
    {
        return PRODUCTS;
    }
}

Please refer to the attached project for detailed code.

Step 4

Creating the Controller

Right click the controller folder and select the Add->Controller menu.

Image 5

It takes you into the Add Controller window, retype the Controller name as ProductController and click the Add button.

Image 6

Controller hasg three types of templates. In this application, select the Empty controller.

When selecting other templates, the controller class will have some default read/write action code.

Step 5

Build the application and make sure no build error has occurred.

Creating the View

Open the ProductController class and right click the Index method and the Add View menu.

Image 7

It takes you into the Add View window.

Image 8

View name: leave the default value (Index)

View engine: leave the default value (Razor view engine). It will create a file name Index with a .cshtml extension.

Select Create a strongly-typed view checkbox and Model class: ProductModel (application should be built before doing this step).

Scaffold Template: Empty and keep default all other fields in this window and click the Add button.

It creates the default Product/Index.cshtml page under the Views folder.

Razor View Engine Syntax – The fundamentals

Character ‘@’

In the HTML markup, we can use ‘@’ instead of ‘<% %>’ for writing C# or VB code. For example:

For a single line C# code DateTime.Now, just add ‘@’ in front of DataTime.Now with HTML markup.

HTML
<p>
    Today: @DateTime.Now
</p>

For multiline code, @{……} is enough to specify the C# code.

C#
@{
    int i = 0;
    i += 10;
}
Layout.cshtml
  • @RenderBody()
  • Renders the content of a page that is not within any named section.

  • @RenderSection("mySectionName")
  • Renders the content of the section within the given name. Sections are mandatory by default, so each page linked to the template will have to declare them.

  • @RenderSection("mySectionName", optional:true)
  • Renders the content of an optional section. The pages that are linked to the template can omit the definition of an optional section.

_Layout.cshtml is the master page of this application and the @RenderBody() part renders the out index.cshtml page.

Index.cshtml

By default, the index.cshtml page has the below code.

C#
@model MVC3Demo.Models.ProductModel
@{
    ViewBag.Title = "Index";
}

Page directives and Inherits attributes etc., have been removed in this MVC3 version.

Custom Helper

Custom helper is also possible to create in Razor, for creating customer helpers, we have to follow the below steps.

Step 8

Add new App_Code folder and right click that folder.

Image 9

The Add New Item window will open, select MVC3 Partial Page (Razor) and name it CustomerHelpers.cshtml.

Image 10

Create custom helper with @helper methodname() {…..} in the CustomerHelper.cshtml page.

XML
@helper ShowTime()
{
    <div>
        Current Time: <strong>@DateTime.Now.ToShortTimeString()</strong>
    </div>
}

And build the project, then the @CustomerHelpers.ShowTime() method can use the view as well as the layout pages.

Refer to the attached application for detailed code in ProductController and Index.cshtml and run the application.

Conclusion

I hope this blog helps you create basic applications using the MVC3 pattern.

I will come up with some other features in MVC3 in my next article.

References:

  1. http://msdn.microsoft.com/en-us/library/ff649643.aspx
  2. http://msdn.microsoft.com/en-us/library/dd381412(VS.98).aspx
  3. http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1491
  4. http://msdn.microsoft.com/en-us/VS2010TrainingCourse_ASPNETMVC3Razor

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Artha is a Technical Lead in Windows Phone, WPF [MVVM, PRISM], ASP.NET [MVC 3.0 & 4.0], C#.NET, VB.NET and ASP.

Windows Phone

Microsoft Developer Network


Published Tools in Visual Studio Galleries


Published Source Codes in CodePlex


Microsoft Virtual Academy Profile


Published Articles in Code Project


Microsoft Certified Professional Developer (MCPD) Microsoft ASP.NET Developer 3.5 (070-564, 070-536, 070-562, 070 315)

Comments and Discussions

 
Questionvery good article Pin
Member 1123306413-Nov-14 21:26
Member 1123306413-Nov-14 21:26 
BugCannot be opened Pin
sridevikhl21-Jan-13 16:05
sridevikhl21-Jan-13 16:05 
GeneralRe: Cannot be opened Pin
Arthanarieaswaran Shanmugaraj27-Feb-13 17:20
Arthanarieaswaran Shanmugaraj27-Feb-13 17:20 
Questionerror Pin
purushottamahire17-Jun-12 22:06
purushottamahire17-Jun-12 22:06 
AnswerRe: error Pin
Arthanarieaswaran Shanmugaraj22-Jun-12 16:20
Arthanarieaswaran Shanmugaraj22-Jun-12 16:20 
GeneralMy vote of 3 Pin
Sridhar Patnayak31-May-12 22:12
professionalSridhar Patnayak31-May-12 22:12 
GeneralRe: My vote of 3 Pin
Arthanarieaswaran Shanmugaraj6-Jun-12 18:22
Arthanarieaswaran Shanmugaraj6-Jun-12 18:22 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey30-May-12 20:51
professionalManoj Kumar Choubey30-May-12 20:51 
GeneralRe: My vote of 5 Pin
Arthanarieaswaran Shanmugaraj6-Jun-12 18:21
Arthanarieaswaran Shanmugaraj6-Jun-12 18:21 
QuestionI kept getting a 404 error Pin
mikelopilato28-Mar-12 7:26
mikelopilato28-Mar-12 7:26 
AnswerRe: I kept getting a 404 error Pin
Arthanarieaswaran Shanmugaraj28-Mar-12 19:20
Arthanarieaswaran Shanmugaraj28-Mar-12 19:20 
GeneralRe: I kept getting a 404 error Pin
mikelopilato29-Mar-12 12:07
mikelopilato29-Mar-12 12:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.