ASP.NET Core 2.2 For Beginners (Part 11): Front-End Frameworks

In this chapter, you will learn how to install front-end libraries using LibMan. LibMan wasn’t developed to replace package managers, such as npm or yarn. If your project uses a package manager then continue to do so. LibMan is available from Visual Studio 2017 version 15.8. You can follow the installation instructions if you want to add client-side libraries locally in your project; this is not necessary in this project since you have added CDN links in the _Layout file.

Bootstrap: This is the most popular library for styling and responsive design. You will use some Bootstrap CSS classes to style the video list and the navigation links. You can find out more about Bootstrap on their site: http://getbootstrap.com.

Installing LibMan and the Frameworks

LibMan is the preferred way to install front-end frameworks in ASP.NET Core 2.2. When the libraries have been installed, they must be referenced from the _Layout view for global access, or in individual views for local access. You can use the environment tag to specify the environment the libraries should be accessible from. You usually want the un-minified libraries in the included Development <environment> Tag Helper for easy debugging, and the minified versions in the excluded Development <environment> Tag Helper for produc­tion builds.

Many times, you can achieve even faster load times if you use Content Delivery Networks (CDNs), servers that have cached versions of the libraries that can be called. You can find information about the Microsoft’s CDNs at:

https://docs.microsoft.com/en-us/aspnet/ajax/cdn/overview.

Four attributes are used to check that the JavaScript libraries have been installed: asp-fallback-test-class, asp-fallback-test-property, asp-fallback-test-value, and asp-fallback-test.

Two of the attributes are used to load an alternative source if the JavaScript libraries haven’t been installed: asp-fallback-src and asp-fallback-href.

Using LibMan to Add Client-Side Libraries

  1. Right click on the project node in the Solution Explorer and select Add-Client-Side Library.
  2. Select the desired provider: cdnjs, file system or unpkg in the Provider dropdown. Use the default cdnjs
  3. Enter the name of the library you want to install into the Library Type jquery and select the JQuery option in the options list.
  4. Enter a target location where the library will be installed into the Target Location textbox, or use the default location.
  5. Click the Install
  6. Repeat step 1-5 for Bootstrap ([email protected]), JQuery Validate ([email protected]) and JQuery Validation ([email protected]).
  7. Open the Startup class and make sure that the Static Files middleware is called above the UseMvc method call in the Configure method to enable loading of CSS and JavaScript files.

app.UseStaticFiles();

  1. Open the _Layout view and add two <environment> Tag Helpers below the <title> element inside the <head> element. The first should only include the Development environment, and the second should exclude the Development You can change environment in the project settings. In these two Tag Helpers, you specify CSS libraries you want to load when the view loads.

<environment include="Development">
</environment>

<environment exclude="Development">
</environment>

  1. Add the un-minified Bootstrap CSS library inside the include Development environment tag and the minified version to the exclude Development tag.

<environment include="Development">
    <link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
</environment>

<environment exclude="Development">
    <link href="~/lib/twitter-bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</environment>

  1. Repeat step 6 at the bottom of the <body> element. In these two Tag Helpers, you specify JavaScript libraries you want to load when the HTML has finished loading.
  2. Add the js, jquery.js, jquery.validation.js, and jquery.validation.unobtrusive.js libraries and their minified versions to the <environment> Tag Helper you added in the <body> element.

<environment include="Development">
        <script src="~/lib/jquery/jquery.js"></script>

        <script src="~/lib/jquery-validate/jquery.validate.min.js"></script>

        <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

        <script src="~/lib/twitter-bootstrap/js/bootstrap.js"></script>
</environment>

<environment exclude="Development">
        <script src="~/lib/jquery/jquery.min.js"></script>

        <script src="~/lib/jquery-validate/jquery.validate.min.js"></script>

    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

    <script src="~/lib/twitter-bootstrap/js/bootstrap.min.js"></script>
</environment>

 

The complete dependency list in the libman.json file:

{
    "version": "1.0",
    "defaultProvider": "cdnjs",
    "libraries": [
    {
        "library": "[email protected]",
        "destination": "wwwroot/lib/jquery/"
    },
    {
        "library": "[email protected]",
        "destination": "wwwroot/lib/twitter-bootstrap/"
    },
    {
        "provider": "cdnjs",
        "library": "[email protected]",
        "destination": "wwwroot/lib/jquery-validation-unobtrusive/"
    },
    {
        "provider": "cdnjs",
        "library": "[email protected]",
        "destination": "wwwroot/lib/jquery-validate/",
        "files": ["jquery.validate.min.js"]
    }]
}

Styling with Bootstrap

Let’s add a navigation bar in the _Layout view, and style it and the video list in the Index view, using Bootstrap.

The navigation bar for an anonymous user:

The navigation bar for a logged in user:

Adding a Navigation Bar

  1. Open the _Layout
  2. Remove the <partial> Tag Helper.

<div>
    <partial name="_LoginLinks"/>
</div>

  1. Add a <nav> element at the top of the <body> element and decorate it with the navbar navbar-expand-lg, navbar-light and bg-light Bootstrap classes, to create the navigation bar placeholder.

 <nav class="navbar navbar-expand-lg navbar-light bg-light"></nav>

  1. Add an anchor tag at the top of the <nav> element. This link will take the user back to the application root (the Index view) if clicked. Add the Bootstrap class navbar-brand and the text Video Application to it.

<a class="navbar-brand" href="/">Video Application</a>

  1. Add a <button> element below the brand <a> element. Add the navbar-toggler class and the the data-toggle, data-target and aria-controls, aria-expanded and aria-label attributes to it to enable toggling between the regular menu and the “hamburger” menu for amaller devices. Add a <span> decorated with the navbar-toggler-icon class to display the three horizontal “hamburger” lines on the button.

<button class="navbar-toggler" type="button"
    data-toggle="collapse" data-target="#navbarNavDropdown"
    aria-controls="navbarNavDropdown" aria-expanded="false"
    aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>

  1. Add a <div> element blow the button that will hold the collapsible/expandable menu items. Decorate the element with the collapse and navbar-collapse classes and add the id attribute with the name from the data-target attribute on the button. Don’t forget that ids souldn’t have the hash symbol (#).

<div class="collapse navbar-collapse" id="navbarNavDropdown"></div>

  1. Add an unordered list to the <div> and add the navbar-nav and ml-auto classes to it. The ml-auto class pushes the content to the right in the navigation bar.

<ul class="navbar-nav ml-auto"></ul>

  1. Add a <partial> Tag Helper inside the <ul> element to bring in the content from the _LoginLinks partial view. Use the name attribute to name the partial view.

<partial name="_LoginLinks" />

  1. Open the _LoginLinks partial view.
  2. Cut out the Razor expression that fetches the user’s name, and paste it at the top of the form. Delete the <div>.

<form method="post" asp-controller="Account" asp-action="Logout">
    @User.Identity.Name
    <input type="submit" value="Logout" />
</form>

  1. Add the Bootstrap classes btn, and btn-danger to the submit button to style it.

<input type="submit" value="Logout" class="btn btn-danger" />

  1. Add the Bootstrap classes btn, btn-outline-dark and mr-sm-1 to the login <a> element to turn the links into button and add a right margin to separate the buttons. Add an <li> element decorated with the nav-item class around the <a> element to turn it into a list item.

<li class="nav-item">
    <a asp-controller="Account" asp-action="Login" class="btn btn-outline-dark mr-sm-1">Login</a>
</li>

  1. Add the Bootstrap classes btn and btn-outline-dark to the registration <a> element to turn the links into button. Add an <li> element decorated with the nav-item class around the <a> element to turn it into a list item.

<li class="nav-item">
    <a asp-controller="Account" asp-action="Register" class="btn btn-outline-success">Register</a>
</li>

  1. Save all files and start the application without debugging (Ctrl+F5). A navigation bar with the brand name and the links should be visible at the top of the view.

The complete markup for the _LoginLinks partial view:

@using Microsoft.AspNetCore.Identity
@inject SignInManager<VideoUser> SignInManager
@inject UserManager<VideoUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    // Signed in user
    <form method="post" asp-controller="Account" asp-action="Logout">
        @User.Identity.Name
        <input type="submit" value="Logout" class="btn btn-danger"/>
    </form>
}
else
{
    // Anonymous user
    <li class="nav-item">
        <a asp-controller="Account" asp-action="Login" class="btn btn-outline-dark mr-sm-1">Login</a>
    </li>

    <li class="nav-item">
        <a asp-controller="Account" asp-action="Register" class="btn btn-outline-success">Register</a>
    </li>
}

 

The navigation bar markup in the _Layout view:

<nav class="navbar navbar-expand-sm navbar-light bg-light">
    <a class="navbar-brand" href="/">Video Application</a>

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav ml-auto">
            <partial name="_LoginLinks" />
        </ul>
    </div>
</nav>

Styling the Index View

Let’s make the video list a bit more appealing by adding Bootstrap classes to make them appear like cards. The image below shows the end result.

  1. Open the _Layout
  2. Add the container-fluid class to the div surrounding the RenderBody

<div class="container-fluid">
    @RenderBody()
</div>

  1. Comment out the <footer> element and its content.
  2. Open the Index
  3. Add the Bootstrap classes btn and btn-success to the Create link in the Index This should turn the button green, with the default Bootstrap theme.

<a class="btn btn-success" asp-action="Create">Create</a>

  1. Add a <div> element around the foreach loop and decorate it with the card-deck class to create a container for the cards that will be added by the loop. Also, add the mt-3 class to add a top margin to the container to push it down from the navigation bar.

<div class="card-deck mt-3"></div>

  1. Open the _VideoPartial partial view.
  2. Delete all content except the @model
  3. Add a <div> element and decorate it with the card class to create a card. Add the border-success class to add color to the border and the mb-3 class to add a bottom margin.

<div class="card border-success mb-3"></div>

  1. Add a <div> element inside the previous <div> and decorate it with the card-header class to add a header to the card. Add the bg-success and and border-success classes to add some color to the card. Add the title from the model inside the <div>.

<div class="card-header bg-success border-success">@Model.Title</div>

  1. Add a <div> beow the header <div> and decoreate it with the card-body class to create a container for the card content.

<div class="card-body"></div>

  1. Add a <p> elemenmtn decorated with the card-text class below the previous <div> and add the genre from the model to it.

<p class="card-text">@Model.Genre</p>

  1. Add links to the Details and Edit views for each video card.

<a asp-action="Details" asp-route-id="@Model.Id">Details</a>
<a asp-action="Edit" asp-route-id="@Model.Id">Edit</a>

  1. Remove the @section footer block from all views that have the block.
  2. Save all files and start the application without debugging (Ctrl+F5). The videos should be displayed in cards.

The complete markup for the _VideoPartial view:

@model VideoViewModel

<div class="card border-success mb-3">
    <div class="card-header bg-success border-success">@Model.Title</div>

    <div class="card-body">
        <p class="card-text">@Model.Genre</p>
        <a asp-action="Details" asp-route-id="@Model.Id">Details</a>
        <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a>
    </div>
</div>

Adding Client-Side Validation

To take advantage of client-side validation, you only have to add the jquery, jquery.
validate
, and jquery.validate.unobtrusive JavaScript libraries. You have already added the libraries in a previous section, so now you only have to check that the validation works.

Pay attention to the URL field in the browser as you click the Login, Edit, and Create buttons when you try to enter invalid data (you can for instance leave one of the text fields empty). The URL should not refresh, because no round-trip is made to the server.

  1. Run the application without debugging (Ctrl+F5).
  2. Click the Edit button in the Index view; this should display the Login If you’re already logged in then click the Logout button and repeat this step.
  3. Leave the Username field empty and click the Login Pay attention to the URL; it should not refresh. An error message should be displayed in the form.
  4. Log in with correct credentials.
  5. Clear the Title field and click the Edit Pay attention to the URL; it should not refresh. Two error messages should be displayed, one for the validation summary, above the controls, and one beside the text field.
  6. Click the Back to List link to return to the Index

  7. Click the Create button below the video list.
  8. Try to add a video with an empty title. Pay attention to the URL; it should not refresh. The same type of error displayed for the Edit view should be displayed.

Summary

In this chapter, you used Bower to add JQuery libraries to enforce client-side validation, and Bootstrap to style the Index view with CSS classes.

Stay connected with news and updates!

Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.

Subscribe
Close

50% Complete

Two Step

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.