ASP.NET MVC3 Razor

ASP.NET MVC3 Razor

MVC (Model-View-Controller) is a simple architecture where all components are separated into three classes:

  1. Model - Classes that contain data that will be shown to the user.
  2. View - Components that will display the model to the user.
  3. Controller - Components that will handle any interaction with the user.

In the web framework, the user will enter some URL to the MVC application, and the controller, model, and view will handle this request and return the HTML back to the user. The interaction between the browser and the server that has model, view, and controller components is shown in the following figure:

This simple scenario of processing an MVC request is described in the following steps:

  1. The user enters in the browser some URL that is sent to the server, e.g., http://localhost/Product/List.
  2. The user request is analyzed by the framework in order to determine what controller should be called.
  3. The Controller takes the parameters that the user has sent, calls the model to fetch some data, and loads the model object that should be displayed.
  4. The Controller passes the model object to the view.
  5. The View gets data from the model, puts it into the HTML template, and sends the response back to the user browser.
  6. The browser shows the HTML that is received from the server.

Razor View Template

When you create a view component that translates C# data objects to HTML view, you can use several template syntax. Razor is one nice and clean syntax for combining C# and HTML code. In the following listing, you can see a simple example of the Razor syntax:

@{
 string name = "John";
 var dateOfBirth = new { Day = 12, Month = 25, Year = 1980 }; 
 string[] skills = new string[] { "MVC",  "C#", "JQuery", "ASP.NET" };
}

<h2>@name</h2>
<p>Born in year: @dateOfBirth.Year, Skills:</p>
<ul>
@foreach(oSkill in skills){
 <li>oSkill </li> 
}
</ul>
    

In the first part, we have defined a few C# variables, and then we have injected them into the HTML code. The resulting HTML output is shown in the following listing:

<h2>John</h2>
<p>Born in year: 1980, Skills:</p>
<ul>
 <li>MVC</li>
 <li>C#</li>
 <li>JQuery</li>
 <li>ASP.NET</li>
</ul>
    

As you can see, C# code will be discarded and only values from that code will be injected in the HTML template. Putting C# data into HTML with Razor syntax is easy - just put the name of the C# variable with the @ prefix. This works both with simple types and object fields. Even if you have more complex processing such as outputting the list of elements with some loop, the syntax is very clean.

CodeProject: ASP.NET MVC3 Razor With jQuery For Beginners

Create a Wizard in ASP.NET MVC 3