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
- VS 2010
- 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.
Creating an MVC 3 application
Step 1
Language |
Visual C# or Visual Basic |
Target Framework |
.NET Framework 4 |
Installed Templates |
Web |
Template |
ASP.NET MVC 3 Web Application |
Name |
MVC3Demo |
Step 2
After clicking the OK button in the New Project window, the MVC 3 project templates window will open.
Select the Template section which has three application templates:
- Empty
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.
- Internet Application
It creates AccountController, HomeController and related views with code for running with Forms authentication.
- Intranet Application
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.
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.
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.
It takes you into the Add Controller window, retype the Controller name as ProductController
and click the Add button.
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.
It takes you into the Add View window.
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.
<p>
Today: @DateTime.Now
</p>
For multiline code, @{……}
is enough to specify the C# code.
@{
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.
@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.
The Add New Item window will open, select MVC3 Partial Page (Razor) and name it CustomerHelpers.cshtml.
Create custom helper with @helper methodname() {…..}
in the CustomerHelper.cshtml page.
@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:
- http://msdn.microsoft.com/en-us/library/ff649643.aspx
- http://msdn.microsoft.com/en-us/library/dd381412(VS.98).aspx
- http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1491
- http://msdn.microsoft.com/en-us/VS2010TrainingCourse_ASPNETMVC3Razor