4 . ASP.NET MVC4 View Techniques

About this Tutorial

Objectives

Delegates will learn to develop web applications using C# 4.0. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial ASP.NET Web Applications
  • Develop user interfaces using Master Pages, Site Navigation and Themes

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of ASP.Net will also find the content beneficial.

Prerequisites

No previous experience in ASP.NET programming is required. But any experience you do have in programming will help. Also no experience in visual studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview

Estimated Time – 2 hours and 30 minutes

Not what you are looking? Try the next tutorial – ASP.NET MVC4 Implementing Navigation

In this tutorial we will enhance the film application you last worked on in the industrial strength application lab.

We are going to use that online film rental application and see how to display hyperlinks for all the pages. We also will see how to generate and display HTML snippets in ASP.NET MVC4.

How about a training course? View Course Outline.

Lab 1: Defining HTML Helper Methods

Lab 1: Defining HTML Helper Methods

Carrying on from the tutorial that can be found in the solution called FilmsRUsOnline

  1. We are going to add a pagination information class in the FilmsRUsOnline model folder – This will communicate information between the controller and view so that the view knows how to display the page links. Right-click models, select Add>Class and name it PaginationInfo.
    Picborder

    namespace FilmsRUsOnline. Models
    {
     public class PaginationInfo
     {
      public int CurrPage { get; set; }
       public int NumItems { get; set; }
      public int ItemsPerPage { get; set; }
      public int NumPages
      {
       get { return (int)Math.Ceiling((double)NumItems / ItemsPerPage); }
      }
     }
    }
  2. View code file.
  3.  

  4. The controller now needs to send two pieces of information to the viewFilms for the current page and pagination information. So now we’ll define a “wrapper” model class to encapsulate this information.

    using Domain.Entities;
    namespace FilmsRUsOnline. Models
    {
     public class FilmsViewModel
     {
      public IEnumerable Films { get; set; }
      public PaginationInfo PaginationInfo { get; set; }
     }
    }
  5. View code file.
  6.  

  7. Now to update the films controller to send the information to the view.

    public class FilmsController : Controller
    {
     public int PageSize = 3;
     …
     public ViewResult List(int pageNumber = 1)
     {
      var filmsToShow = filmsRepository.Films;
      FilmsViewModel vm = new FilmsViewModel()
      {
       Films = filmsToShow.Skip((pageNumber - 1) * PageSize)
         .Take(PageSize)
         .ToList(),
         PaginationInfo = new PaginationInfo
      {
        CurrPage = pageNumber,
        ItemsPerPage = PageSize,
        NumItems = filmsToShow.Count()
      }
     };
     return View(vm);
     }
    }
  8. View code file.
  9.  

  10. We need to create a HTML helper method to help display the pagination information. HTML helpers’ methods are a quick way generating raw HTML in MVC. There are lots of predefined helpers available and we will our own create custom helpers.

    • Create a new folder in FilmsRUsOnline called htmlhelpers.
    • Add a new class to this called PaginationHelpers.

      using System.Web.Mvc;
      using FilmsRUsOnline.Models;
      namespace FilmsRUsOnline. HtmlHelpers
      {
       public static class PaginationHelpers
       {
        public static MvcHtmlString PaginationLinks(this HtmlHelper html,
           PaginationInfo pinfo,
           Func url)
        {
         String result = "";
         for (int p = 1; p <= pinfo.NumPages; p++)
         {
          if (p == pinfo.CurrPage)
           result += "" + p;
          else
           result += string.Format("{1} ", url(p), p);
         }
         return MvcHtmlString.Create(result);
        }
       }
      }
    • View code file.

Lab 2: Using HTML Helper Methods

Lab 2: Using HTML Helper Methods
  1. The reason we’ve defined HTML helper methods is so that we can use them in our view pages: e.g. html.paginationLinks().
  2. This is only available if you reference the relevant namespace in the view@using FilmsRUsOnline.HtmlHelpers.
  3. We now need to update the view Lists.

    @model FilmsRUsOnline.Models.FilmsViewModel
    @using FilmsRUsOnline.HtmlHelpers
    @{
     ViewBag.Title = "List of films";
     Layout = "~/Views/Shared/_Layout.cshtml";
    }
    @foreach (var film in Model.Films)
    {
     <div class="item">
      <h4>@film.Title</h4>
      <p>Blurb: @film.Blurb</p>
      <p>Rental price: @film.RentalPrice.ToString("c")</p>
     </div>
    }
    <div class="pager">
     @Html.PaginationLinks(Model.PaginationInfo,
        x => Url.Action("List", new {PageNumber = x}))
    </div>
  4. View code file.
  5.  

  6. The Razor engine we are using supports a simplified syntax for defining HTML helper methods and can be done like so.

    • In your project root folder, create a folder.
    • In the folder, add a new Razor View Page.
    • Define a method (with parameters if appropriate).
    • Prefix the method with @helper.
    • An example of this is with a reference to the folder, a class called MyHelpers and a method called Listing().

      @model List

      Employees:
      @MyHelpers.Listing(Model)
  7. Run the application to see the pagination links in action

Lab 3: Improving layout and Appearance

Lab 3: Improving layout and Appearance
  1. We can now enhance our layoutpage – by using @RenderSection() to represent optional content and @RenderBody() to represent main body content in the shared folder “_layout.cshtml”.

    <!DOCTYPE html>
    <html>
     <head>
      …
     </head>
     <body>
      <header>
       @RenderSection("header")
      </header>
      <nav>
       @RenderSection("menu", required:false)
      </nav>
      <div id="content">
       @RenderBody()
      </div>
     </body>
    </html>
  2. View code file.
  3.  

  4. We now can update the List.cshtml to work with the new layout with @RenderSection working with @section header.

    @{
     Layout = "~/Views/Shared/_Layout.cshtml";
     …
    }
    @section header {
     Films R Us
    }
    @section menu {
     TODO: Menu
    }
    @foreach (var film in Model.Films)
     etc…
  5. View code file.
  6.  

  7. We can now update the Site.css in the Content folder to improve user experience.

    … original CSS rules here …
    header
    {
     color: White;
     background-color: #8888ff;
     font-size: 24pt;
     padding: 15px;
     text-align: left;
     border-bottom: 2px solid #111;
    }
    nav
    {
     float: left;
     width: 120px;
     padding: 0 5px 0px 15px;
    }
    etc…
  8. View code file.
  9.  

  10. And now run the application to see what has been created.
    Coolpage

Lab 4: Defining and using Partial Views

Lab 4: Defining and using Partial Views

 

  1. What is a partial view? – A partial view contains some reusable view real-estate.
  2. What are the advantages of using partial views?

    • Modularity.
    • Clarity.
    • Maintenance.
    • Consistency.
    • Simplicity.
  3. To create a partial view.

      • In FilmsRUsOnline right click Views>Shared folder.
      • Select Add View and in the dialog select the checkbox partial view.
      • Name this _FilmSummary.
      • Also check the strongly-typed view using Film (Domain.Entities).

    Partial View

  4. Now in the newly created view, add the following that creates a HTML fragment.

    @model Domain.Entities.Film
    <div class="item">
     <h4>@Model.Title</h4>
     <p>Blurb: @Model.Blurb</p>
     <p>Rental price: @Model.RentalPrice.ToString("c")</p>
    </div>
  5. View code file.
  6.  

  7. To use a partial view in a full page use either Html.Partial() which returns a string to the calling page and the calling page can manipulate the string; or Html.RenderPartial() which writes the result directly to the webpage and returns void to the calling page.
  8. For our List.cshtml we will use @Html.Partial.

    @model FilmsRUsOnline.Models.FilmsViewModel
     …
    @foreach (var film in Model.Films)
    {
     @Html.Partial("_FilmSummary", film)
    }
  9. View code file.

Lab 5: Bundling and Minification

Lab 5: Bundling and Minification

Bundling and minification are two new features in ASP.NET 4.5, to improve request load time. They allow JavaScript files to be handled in a faster and more efficient way,

Bundling:

  • Groups related files (e.g. JavaScript files and CSS style sheets) into a cohesive bundle.
  • Bundles can be downloaded in a single HTTP request.

Minification:

  • Reduces the size of JavaScript files, by removing unnecessary space and by replacing identifiers with single letters.
  • Speeds up download time for JavaScript files.
  1. How Bundling works? – Global.asax.cs kicks off the bundling at app start-up.

    protected void Application_Start()
    {
     …
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     …
    }
  2. The App_start/BundleConfig.cs file creates all the bundles and already bundles a lot of standard files.

    public class BundleConfig
    {
     public static void RegisterBundles(BundleCollection bundles)
     {
      bundles.Add( … a ScriptBundle … );
      bundles.Add( … a ScriptBundle … );
      bundles.Add( … a StyleBundle … );
      bundles.Add( … a StyleBundle … );
      …
     }
    }
  3. To create a script bundle.

    ScriptBundle sb1 = new ScriptBundle("~/bundles/jquery");
    ScriptBundle sb2 = new ScriptBundle("~/bundles/jqueryval");
  4. Add files to the script bundle – call include() and pass any number of .js files, use {version} for a version number and * for wildcards e.g.

    sb1.Include("~/Scripts/jquery-{version}.js");
    sb2.Include("~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*");
  5. You can then add the script bundles to the bundle collection.

    bundles.Add(sb1);
    bundles.Add(sb2);
  6. To better write these bundles above we use this code instead.

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
       "~/Scripts/jquery-{version}.js"));
    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
       "~/Scripts/jquery.unobtrusive*",
       "~/Scripts/jquery.validate*"));
  7. Bundle

  8. To create a style bundle; the process is much the same as for a script bundle except for using the word StyleBundle instead of ScriptBundle.

    bundles.Add(new StyleBundle("~/Content/themes/base/css")
      .Include("~/Content/themes/base/jquery.ui.core.css",
        "~/Content/themes/base/jquery.ui.resizable.css",
        "~/Content/themes/base/jquery.ui.selectable.css", … ) );
  9. View code file.
  10.  

  11. To reference these in your views, you can use Scripts.Render() and Styles.Render() remembering to specify the name of the bundles. Below is a typical _Layout.cshtml file appears.


    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
     …
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
  12. Controlling Bundling and Minification.

    • During development, you might want to disable bundling and minification.
    • You can disable this in Web.config.

      <system.web>
      <compilation debug="true" />
       …
      </system.web>
    • You can also override the Web.Config setting pro-grammatically.

      public static void RegisterBundles(BundleCollection bundles)
      {
       …
       BundleTable.EnableOptimizations = false;
      }

In the next tutorials we will enhance the application further by implementing navigation through the application using genres of films to do this.

 

Well done. You have completed the tutorial in the MVC4 course. The next tutorial is

5. ASP.NET MVC4 Implementing Navigation


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top