Building Apps with ASP.NET MVC 4 - Module 3 - Razor Views

Notes taken from Razor Views module in Building Applications with ASP.NET MVC 4 course on PluralSight.

  1. Razor Basics
  2. Code Expressions
  3. Code Blocks
  4. Layout Views
  5. HTML Helpers

Overview
Razor Syntax - how to transition between C# code and mark up inside of a Razor view.
HTML Helpers - keep view simple and how to work with a layout view that defines the structure of our user interface.
Security - avoid cross-site scripting attacks and HTML encoding
Partial Views

Razor Basics
Template + Data = Generated Output
.cshtml extension

<div>
	@Model.Name
</div>
<div>
	@Model.City, @Model.Country
</div>

Properties from model are placed in a view to display data.

Right-click on controllers folder and Add New…Controller
With MVC controller with empty read-write actions. This creates scaffolding to edit, delete, or modify records. None of the code is there yet but we can put in as we go along.

Add a class in the Models folder, called RestaurantReview.cs and a few properties to the class. One day these will be in a database, but for now we'll use static data for educational purposes.

namespace OdeToFood3.Models
{
    public class RestaurantReview
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public int Rating { get; set; }

    }
}

Add using OdeToFood3.Models to make it in the correct namespace.

Looking for Views/Reviews folder

Right-click inside a controller action, such as Index and click Add View…

 

List is the scaffolding, a basic UI for you. Gives you a starting point. The list assumes you have multiple data items to display. VS builds a table for you for the data items.

Create a model instance in Index() action as follows, and then return the model to the view:

var model =
       from r in _reviews
       orderby r.Country
       select r;

	return View(model);

Save everything and do a build and then you should see a table with all your items displayed in the browser.

Back to Top

Code Expressions

You can edit this just like any HTML page. Razor is smart enough to find the @ expressions and pull in the data.

You can modify the HTML and save the View. You don't have to rebuild the solution. Just hit refresh in the browser and your changes will display.

@model IEnumerable<OdeToFood3.Models.RestaurantReview>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Country)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Rating)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Country)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Rating)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

We are showing the latest @Model.Count() reviews. This will display the following, in the browser

We are showing the latest 3 reviews.

@VirtualPath - displays the relative path of the file in the browser.

 Razor automatically HTML encodes all strings to avoid cross-site scripting attacks

 @Html.Raw(item.City) - does not encode, just raw HTML, very dangerous, avoid XSS attacks.

 @item.Rating / 10 - 2 ways to interpret Razor will assume it is text. Explicit code to divide by 10,

@(item.Racine / 10) - divides rating by 10.

 Back to Top

Code Blocks

Keep the View Simple! Avoid a lot of complicated logic in Views.

Example:

 

@{
    ViewBag.Title = "Index";
}

@: tells Razor that after that is literal text such as:

@foreach (var item in Model)
{
@:Review // will display as literal text

Back to Top

Layout Views

_Layout.cshtml - Can be found in ~/Views/Shared/  folder

(similar to the master pages in the old web forms, head section and nav)

 How does the MVC runtime know to use this _layout.cshtml?

_viewstart.cshtml found in Views folder

 @RenderBody is required

@RenderSection is optional

@RenderSection

@section featured{

        We are showing the @Model.Count() reviews.

}

Define these sections anywhere

Create a new ActionLink for Review page in navigation. On _Layout.cshtml, in Shared folder,

Copy last ActionLink,

 <li>@Html.ActionLink("Contact", "Contact", "Home")</li>

 And change it as follows

@Html.ActionLink("The text you want to display", "The Action on the controller", "The name of the controller you want to reach")

 Example: For the Reviews page,

<li>@Html.ActionLink("Reviews", "Index", "Reviews")</li>

This reads: Display the text, Reviews. Use the Index method on the Reviews controller.

Save and build the solution, and then open in browser,

Now the Reviews link will appear on every page that uses the _Layout.cshtml page.

Back to Top

HTML Helpers

Html is a property of the ViewPage base class

  • Create inputs
  • Create links
  • Create forms

 

The Html.ActionLink is one of many HTML Helpers we can use to do the above actions.

 

The Html Helpers are quite powerful, for example,