ASP.NET MVC Razor

By | June 25, 2011

The new ASP.NET MVC Razor view engine is pretty cool. 🙂
Here are some examples:

Namespaces:

 
@using MyProject.Entities

Define model type:

 
@using MyProject.Entities
@model User

Create functions:

 
@functions {
    public string GetSomething(User usr) 
    {
        return usr.Name;
    }
}

Templating:

 
// In your template
<html>
...
@RenderSection("MyContent", true) // true = required
<br />
@RenderSection("MyFooter", false) // false = not required
...
</html>

// In your site
@{
    Layout = "~/Views/Shared/YourTemplate.cshtml";
}

@section MyContent {
   <p>hello!</p>
}
@section MyFooter {
   <p>Footer</p>
}

Output model data:

<table>
  <tr>
    <td>Firstname</td>
    <td>@Model.Firstname</td>
  </tr>
  <tr>
    <td>Lastname</td>
    <td>@Model.Lastname</td>
  </tr>
</table>

Input fields with labels:

<table>
   <tr>
      <td>@Html.LabelFor(m => m.Firstname)</td>
      <td>@Html.TextBoxFor(m => m.Firstname)</td>
   </tr>
   <tr>
      <td>@Html.LabelFor(m => m.Lastname)</td>
      <td>@Html.TextBoxFor(m => m.Lastname)</td>
   </tr>
</table>