Tag Archives: HTML

Tag Helper Not Working?

I recently had an issue where I was trying to use a tag helper that wasn’t correctly rendering. The HTML that I had (which was trying to call MyController.MyAction) was this:

            <form asp-controller="My" asp-action="MyAction" method="post">
                <input type="submit" value="Do Crazy Stuff!" />

This wasn’t working. The first step when a tag helper isn’t working is always to check the rendered HTML. Tag Helpers should be converted to proper HTML – if they’re actually sat on the page as a tag helper then nothing will happen, because Chrome and Firefox don’t know what the hell a tag helper is.

The rendered HTML should look something like this

<form method="post" action="/My/MyAction">
    <input type="submit" value="Do Crazy Stuff!">
    <input name="__RequestVerificationToken" type="hidden" value="requestverficationtokendsldjlcjsoihcnwoncwoin">

However, I was seeing the folllowing:

<form asp-controller="My" asp-action="MyAction" method="post">
    <input type="submit" value="Do Crazy Stuff!">

Like I said – this is no good, as browsers don’t know what to do with “asp-controller” et al.

But Why?

Having done some research, it looks like (pretty much) the only reason for this is that you (or I) don’t have the following line in the _ViewImports file:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Or, if you do have it, then for whatever reason, the _ViewImports file itself can’t be located.

For any Regular Readers* of this blog, you may have noticed this post regarding setting up a project to use feature folders.

One of the interesting features about _ViewImports, is that is applies to the folder that it’s in, and any sub folders; my folder structure looked like this:

- Feature1
-- Index.cshtml
-- Feature1.cshtml
- Feature2
-- Index.cshtml
-- Feature2.cshtml
- Views
-- _ViewImports
-- Shared

As a result, the _ViewImports will only apply inside the Views folder.

The Solution(s)

I can see three possibilities here. Each has benefits and drawbacks.

Create a Symbolic Link

One possibility is to Create a symbolic link between the _ViewImports in the views directory and the feature folder. Launch a command prompt (as admin):

C:\Project\src\MyApp\Feature1>mklink _ViewImports.cshtml ..\Views\_ViewImports.cshtml

symbolic link created for _ViewImports.cshtml <<===>> ..\Views\_ViewImports.cshtml

This works fine, but symbolic links can cause issues; especially if you’re copying code around (for example, with a source control system).

Just copy the file

Obviously, you could simply copy the _ViewImports file to the relevant directory. The benefit of this is that each folder only has the relevant imports for that folder; the downside being that you need to maintain all of these (in practice, the file shouldn’t be huge and complex, so this may be the easiest option).

Parent Directory

Finally, you could simply introduce a parent folder; for example:

- Features
-- _ViewImports
-- Feature1
--- Index.cshtml
--- Feature1.cshtml
-- Feature2
--- Index.cshtml
--- Feature2.cshtml
- Views
-- Shared

This is probably my favourite solution – it gives you the best of both worlds, but it does mean that you need to re-structure your solution.




* I’m curious as to whether anyone does read this on a regular basis. Most of the traffic seems to come from Google. If you are a regular reader then please drop a comment.

CSS Animations Sprite Sheet

I’ve recently been investigating the prospect of creating a web-site, where an animation (admittedly a cheesy one) is played out when you load the page. My idea was that two sprites would walk to the centre of the screen. I was actually thinking to mimic something like Manic Miner. Initially, I thought I’d probably need to do some messing around with image manipulation in Javascript, but this gave me the idea that I might be able to run the entire thing through CSS.

Sprite Sheet

The first thing that you need to get is something to animate. The principle of a sprite sheet is that you have many images in a single image file. This is simply a speed trick – it’s faster to pull down a single image, and cache it, than to constantly load separate images for each part of the animation.

If you have separate images, then for this post to work for you, you’ll need to combine them into a single sprite sheet. The tool suggested in the video above is Sprite Sheet Packer. I’ve used this before, and it does the job – you can also do this manually (although you would have to be careful about the spacing).

Now that we have a sprite sheet, we can add it to our project; in my case, I’ve put it in wwwroot\assets.

Let’s talk about how we can layout our page, and animate it; we’ll start with the HTML.


The HTML here is the simplest part: we just want two divs:

<div id="testdiv"></div>
<div id="testdiv2"></div>

That’s all the HTML; everything else is CSS; let’s start with the animation.


Onto the CSS, which is the crux of the whole thing. Let’s start with the @keyframes. This is the part where you can actually define an animation. In our case, we’ll need three of them: one to move the sprite left, one to move it right, and one to animate it.

Move Left & Right

The animation to move an element on the screen is pretty straightforward, you just tell it where to start, and where to stop:

@keyframes moverightanimation {
    from { 
        left: 10%; 
    to {
        left: calc(50% - 25px);

@keyframes moveleftanimation {
    from {
        left: 90%;
    to {
        left: calc(50% + 25px);

As you can see, you can start (or stop) at an absolute position (10px for example), or a percentage, or a calculated value.


The animation is a bit strange; here’s the code:

@keyframes move {
    100% {
        background-position: -72px, 0px;

What this is doing is setting the final position to be negative the width of the full sprite sheet (this will only work for horizontal sheets). We’ll then tell it to step through the images in the element itself. Here’s the CSS for one of the divs:

#testdiv {
    position: absolute;
    left: 20%;
    top: 300px;
    width: 24px;
    height: 30px;    
    animation: moverightanimation 4s forwards, move 1s steps(3) infinite;
    background: transparent url('../assets/spritesheet.png') 0 0 no-repeat;    

Here, we’re calling multiple animations (moverightanimation and move); for the move, we’re specifying a step – that is, we’re telling it that it needs to get from where it currently is, to 100% over 3 steps, and there are 3 sprites in my sprite sheet, so it will helpfully divide one by the other and come up with a value to increase by each time.

The opposite call does almost the same:

#testdiv2 {
    position: absolute;
    left: 80%;
    top: 300px;
    width: 24px;
    height: 30px;    
    animation: moveleftanimation 4s forwards, move 1s steps(3) infinite;
    background: transparent url('../assets/spritesheet2') 0 0 no-repeat;


As someone who spends as little time as they can messing with UI and CSS, I thought this was a fun little exercise.

CORS Errors while playing with the HTML Canvas

In this post, I wrote about how you might draw a graph using the HTML canvas; my next step was to make that more efficient; however, upon trying to import a Javascript module into my script:

import animatedGraphics from './animatedGraphics';

I started getting this error:

Access to script at ‘file:///C:/repos/webanimations/animated-columns-optimised/columns.js’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

After a bit of digging, I uncovered a feature of ES6 that prevents opening this directly in a browser.

Hosting the site locally

The issue is caused because the file is being opened directly; so there seemed to be a couple of ways around this: one is to disable the security in Chrome, although try as I might, I couldn’t manage to get it to give up the ghost: I tried various combinations around the –disable-web-security flag of Chrome.

The second option is to host the site locally. For a brief moment I considered using something like IIS Express; but fortunately, I came across this tool that hosts a site locally for you.

It can be installed as an npm package:

npm install --global http-server

Once installed, you just navigate to the relevant directory, and type http-server:

Starting up http-server, serving ./
Available on:
Hit CTRL-C to stop the server

You can then navigate to your specific page; for example:

And no more CORS error (doesn’t quite work yet, but that’s a whole different story).

Drawing Custom Graphs in HTML and Javascript

While recently playing with the HTML Canvas again, it occurred to me that this power could be used for evil (or statistics are it is commonly known these days).

In this post, I’m going to draw an animated chart using the HTML Canvas and Javascript.

Let’s start with the HTML:

<!DOCTYPE html>
    <link rel="stylesheet" type="text/css" href="test.css">
    <script src="test.js"></script>
<body onload="doDrawing()">
    <canvas id="canvas">

Again, as with my previous post (linked above), I’ll remind you that this will not cope with screen resizing. The CSS, again, isn’t much to write home about:

* { 
canvas {  
    display: block;    


Finally, we come to the Javascript: this is a bit more involved, so I’ll break it down into the individual functions; we’ll start with the top level one:

const doDrawing = () => {
    var c = document.getElementById("canvas");
    c.width = window.innerWidth;
    c.height = window.innerHeight;
    var ctx = c.getContext("2d");    
    drawGraphTop(50, 5, 500);
    drawColumn(100, 500, 4, 'January');
    drawColumn(150, 350, 5, 'February');
    drawColumn(200, 150, 6, 'March');

All we’re doing here is getting a handle to the canvas, setting the height and width so that we fill the screen, and then calling some functions to do the drawing. The helper method to get the context is trivial, but for completeness:

function getContext() {
    var c = document.getElementById("canvas");    
    var ctx = c.getContext("2d");        
    return ctx;

There’s not much to explain here, we’re just getting the context from the canvas and returning it – thereby saving 3 lines of code each time we do that. The drawGraphTop function is a little more interesting:

const drawGraphTop = (top, interval, width) => {
    let ctx = getContext();
    ctx.rect(1, top, width, 2);
    let stage = width / interval;
    for (let i = 0; i <= interval; i++) {
        ctx.rect(i * stage, top, 2, 5);

The idea here is that we display a flat, horizontal line across the top of the screen, with markers. There is no line method on the canvas context, so a flat rectangle is the best we can do.

The more complex method is the drawColumn method (technically, it isn’t actually drawing columnns – but they still feel like columns – at least, more than rows):

const drawColumn = (top, target, speed, label) => {
    let ctx = getContext();
    let x = 10;    
    let directionHorizontal = speed;

    let intervalHandle = setInterval(() => {
        const buffer = 15;
        const height = 30;
        let showText = false;
        ctx.clearRect(1, top - 1, target + buffer + Math.abs(directionHorizontal) + 2, height + 2);

        if (directionHorizontal === 1 && x <= target + buffer) {
        } else if (directionHorizontal > 0 && x >= target + buffer) {
            directionHorizontal = -1;
        } else if (directionHorizontal < 0 && x <= target) {
            directionHorizontal = 0;
            showText = true;            

        x += directionHorizontal;
        ctx.rect(1, top, x, height);

        if (showText) {                        
            ctx.fillText(label, 10, top + 20);
    }, 1);

There is quite a lot to this; let’s focus on the interval; we take a handle to the interval, so that we can cancel it when we’ve finished drawing.

The first thing we do with the context is call beginPath – this allows us to group a series of updates into a single screen update; then we’re clearing an area, just wide of, the size of the rectangle.

We then have a conditional check – if we’re heading right, and have yet to reach the target (which has a small buffer appended for the purpose of animation), then this drops through to the code below; if we’ve reached that then we change direction; and when we’re back to the actual target, we cancel the update and set a flag to make the text appear.

Subsequently, we draw the (horizontal) column and, if we’ve finished, display the text.

Output and Caveats

It’s worth bearing in mind that the way this code is structured is probably not the best for performance – ideally, you would have a sort of game loop and draw, and then update the entire screen in one go.


You can find the code for this here.

Force React Components to sit Side-by-Side

For anyone that knows me, they’ll know that UI and UX is not exactly my strong suit. If I had my way, we’d all just use console applications like this:

>placeorder /productcode coffee /quantity 1

Unfortunately, the trend seems to have gone a different way, and now we have CSS. CSS is a brilliant idea; however, you need to be able to visualise what you want your stuff to look like first.

Anyway, onto this post. If you know anything about CSS or Bootstrap, then you’ve probably already read everything that could interest you about this post!

In my latest project, I have a search box, and I wanted to line up the controls on the screen like this:

Search         [Search Text]        [Search Button]

I’m using React, so the original code looked like this (more or less):

<input type='text'/>
<SimpleButton buttonAction={props.searchAction} buttonLabel="Search" />            

And it rendered like this:

Search         [Search Text]        
[Search Button]

My first gambit was to define a CSS style (so I can now put “Front End Developer” on my CV):

.rowLine {

And I changed the HTML to look like this:

<div className='rowLine'>
    <input type='text'/>
    <SimpleButton buttonAction={props.searchAction} buttonLabel="Search" />            

That worked, and I copied most of it from here. So now I’ve updated my CV to “Senior Front End Developer”.

It then occurred to me that, as good as this looks, there’s probably something in Bootstrap, and if there is, then my web page can look like the rest of the internet. It turns out I was right:

<div className="form-group row">
    <label htmlFor="searchText" className="col-sm-2 col-form-label">Search</label>
    <div className="col-sm-8">
        <input id="searchText" className="form-control" type='text'
                    placeholder="e.g. Goats" />
    <div className="col-sm-2">
        <SimpleButton buttonAction={props.searchAction} buttonLabel="Search" />            

You may notice that React has its own “for” property, called “htmlFor”.

Disclaimer / Apology

As usual, please take everything you read in my blog with a healthy dose of salt. If you are a front end developer then please take solace in the fact that, despite me being facetious, I really need frameworks like Bootstrap, because I would never think to change the colour of a button, or to align the sizes.

This was all so much simpler in the days of Turbo Pascal / Turbo C, where you would draw your buttons using the ANSI character set!





Using View Models in Blazor

Being new to Blazor (and Razor), the first thing that tripped me up was that the view seemed divorced from the rest of the application. In fact, this is actually quite a nice design, as it forces the use of DI.

For example, say you wanted to create a View Model for your view, you could register that ViewModel in the Startup:

        public void ConfigureServices(IServiceCollection services)
            services.AddTransient<MyViewModel, MyViewModel>();

Note here that you don’t need an interface. If you’re only creating an interface for the purpose of this then that abstraction provides no benefit. That isn’t to say there may not be a reason for having an interface, but if you have one and this is the only place it’s used, you probably should reconsider.

The views in Razor / Blazor (at the time of writing) are *.razor files. In order to resolve the dependency inside the view, you would use the following syntax:

@page "/"
@inject ViewModels.MyViewModel MyViewModel

(Note that @page “/” is only in this snippet to orientate the code.)

You can call initialisation in the view model using something like:

@code {

    protected override async Task OnInitAsync()
        await MyViewModel.Init();

And, within your HTML, you can reference the view model like this:


Magic. Hopefully more to come on Blazor soon.

Creating a Basic Web Site from an Asp.Net Core Empty Project

I recently wanted to do a very quick proof of concept, regarding the use of setInterval versus setTimeout after reading that setTimeout was referable if you were calling the same function very rapidly. I thought I’d note down my journey from File -> New Project to having the POC running so that next time, I don’t have to re-lookup the various parts.

File -> New Project

If you create a brand new Asp.Net Core 2.1 project, select empty project, and then run the generated code, you’ll see this:

This is generated by a line in Startup.cs:

app.Run(async (context) =>
    await context.Response.WriteAsync("Hello World!");

The target here is to get to a situation where the blank app is serving an HTML page with some attached Javascript as fast as possible. Here, I’ve got exactly three steps.

Step 1 – Create the HTML File

The application can only serve static files (HTML is considered a static file) from the wwwroot folder. The internal structure of this folder doesn’t matter, but that’s where your file must go:

The contents of this file are as follows:

<!DOCTYPE html>
    <meta charset="utf-8" />

This won’t actually do anything yet, because by default, Asp.Net Core does not serve static files, nor does it know the enormous significance of naming something “Index”.

Step 2 – Configure Asp.Net

Startup.cs is where all the magic happens; this is what it looks like out of the box:

public class Startup
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        if (env.IsDevelopment())
        app.Run(async (context) =>
            await context.Response.WriteAsync("Hello World!");

The `context.Response.WriteAsync` goes, and instead we tell Asp.Net Core to serve static files, and the call to `UseDefaultFiles` means that it will search for Index or Default files. It’s also worth pointing out that the order of these matters:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    if (env.IsDevelopment())

Now it loads the Index.html. So technically it was only two steps – although we haven’t referenced any Javascript yet.

Step 3 – Adding the javascript… and let’s do something funky

Change the HTML to give the paragraph an ID and an absolute position. Also, reference the file site.js:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <script src="site.js"></script>
    <p id="testElement" style="position:absolute">test</p>

Obviously, without adding site.js, nothing will happen (it also needs to be in wwwroot):

The Javascript code for that new file is here:

var divxPos = 0;
window.onload = function () {
function runCode() {
    var test = document.getElementById("testElement");    
    test.style.left = divxPos++ + 'px';    
    setTimeout(() => runCode(), 50);

If you run it, you’ll find the text running away with itself!

Adding a New Screen to the React Template Project

In this post I started looking into ReactJS. Following getting the sample project running, I decided that I’ve try adding a new screen. Since it didn’t go as smoothly as I expected, I’ve documented my adventures.

The target of this post is to create a new screen, using the sample project inside Visual Studio.

Step 1

Create a brand new project for React:

If you run this out of the box (if you can’t because of missing packages then see this article), you’ll get a screen that looks like this:

Step 2

Add a new tsx file to the components:

Here’s some code to add into this new file:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
export class NewScreen extends React.Component<RouteComponentProps<{}>, {}> {
    public render() {
        return <div>
            <h1>New Screen Test</h1>

The Javascript as HTML above is one of the things that makes ReactJS an appealing framework. Combine that with Typescript, and you get a very XAML feel to the whole web application.

Step 3

Add a link to the Navigation Screen (NavMenu.tsx):

<div className='navbar-collapse collapse'>
    <ul className='nav navbar-nav'>
            <NavLink to={ '/' } exact activeClassName='active'>
                <span className='glyphicon glyphicon-home'></span> Home
            <NavLink to={ '/counter' } activeClassName='active'>
                <span className='glyphicon glyphicon-education'></span> Counter
            <NavLink to={ '/fetchdata' } activeClassName='active'>
                <span className='glyphicon glyphicon-th-list'></span> Fetch data
            <NavLink to={'/newscreen'} activeClassName='active'>
                <span className='glyphicon glyphicon-th-list'></span> New screen

If you run this now, you’ll see the navigation entry, but clicking on it will give you a blank screen. It is just that scenario that motivated this post!

Step 4

Finally, the routes.tsx file needs updating so that it knows which screen to load when:

import * as React from 'react';
import { Route } from 'react-router-dom';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import { NewScreen } from './components/NewScreen';
export const routes = <Layout>
    <Route exact path='/' component={ Home } />
    <Route path='/counter' component={ Counter } />
    <Route path='/fetchdata' component={FetchData} />
    <Route path='/newscreen' component={NewScreen} />

Create CSS effect to “Shine” a button border

Imagine that you have an HTML button or element on a page and you would like an effect where the border shines all around the perimeter. this provides an excellent example of an effect of the entire element shining, and this post will largely be based on that code.


CSS has the concept of an animation, to define it, use the following syntax:

.growOnHover:hover:after {
    animation: growAnimation 1s;

Here is the HTML referencing this:

<a href="#" class="growOnHover">Grow</a>

Tge “growAnimation” refers to a KeyFrame:

@keyframes growAnimation {
    from {width: 100px; height: 100px;}
    to {width: 110px; height: 110px;}

The effect

The effect that I want is for a light to run around the circumference of the button when it’s hovered over. In this case, instead of animating from .. to, we can specify at which stage a particular section of the animation kicks in.

.borderShine:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 5;
  height: 5;
  opacity: 0;  

  border-radius: 1;

  background: rgba(255, 255, 255, 10);

.borderShine:hover:after {
  animation: shineAnimation 2s 1;  

@keyframes shineAnimation {
  0%   {left: 0; top: 0; width: 2; height: 2; opacity: 0}
  10%  {width: 100; height: 2}  
  20%  {left: 98; top: 0; width: 2; height: 2}
  25%  {opacity: 1;}
  30%  {height: 100}
  40%  {left: 98; top: 98; height: 2}
  50%  {left: 0; top: 98; width: 100}
  55%  {opacity: 1;}
  60%  {left: 0; top: 98; width: 2; height: 2}
  70%  {left: 0; top: 0; width: 2; height: 100}
  80%  {left: 0; top: 0; width: 2; height: 2}
  100% {opacity: 0;}

There are a few useful things to remember here:

  • The animation is a transition between the state that the screen is currently in, and the state that you want it to be in; so, for example, the opacity set to 1 at 25% will cause the white bar to gradually appear over the steps between the two. The reason that I’ve set opacity twice here is to prevent it from transitioning back too soon.
  • All the figures above are absolute (as my buttons are 100 x 100).





Basic Game Using HTML5 and Javascript

This article discusses how to go about creating a basic game loop in HTML5 / JS and to implement control over a sprite.


A few years ago, when Microsoft released the idea of WinJS, I wrote a game in HTML5/JS (or WinJS – they are not exactly the same).

I recently decided to see if I could write a web game, using just HTML5 and Javascript. This article covers the initial POC and results in a small red square navigating around the screen:

Game Loop

Looking at established game frameworks, they all basically give you the same things:
– A game loop, consisting of an update and draw phase
– Some helper methods for manipulating graphics, or rendering them to the screen

My attempt will be different, I’ll just provide a game loop; here it is:

(function MainGame() {    

    setInterval(function() {
    }, 20);

The loop executes every 20ms, meaning that there are 50 frames per second.


Basically, what the HTML gives us here is a canvas; so the page is very simple:

    <script type="text/javascript" src="./gamelogic.js" ></script>
<body onresize="onResizeGameWindow()">    
    <canvas id="mainCanvas" style="width: 100%; height: 100%"
        onkeydown="onKeyDown()" tabindex="0">

There are two events handled here, because there are two things that the player can do: they can interact with the game (i.e. press a key), and they can resize the browser window. We need to react to both.


Let’s have a look at the draw function next. All this is, is a way of displaying all the objects on the screen in a controlled fashion:

    function Draw() {
        var canvas = document.getElementById("mainCanvas");
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, windowWidth, windowHeight);

        ctx.fillStyle = "#FF0000";
        ctx.fillRect(x, y, iconWidth, iconHeight);

As you can see, there are effectively two parts to this function: firstly, the canvas is cleared, and then the items (in this case, a single item) are drawn to the screen. The important variables here are x and y, because that dictates where the square is drawn; the rest could be hard-coded values.


    function Update() {        
        if (initialised == 0) {

        // Bounce
        if (x >= (windowWidth - iconWidth) 
            && directionX > 0)
            directionX = -1;
        else if (x <= 0 && directionX < 0)
            directionX = 1;

        if (y >= (windowHeight - iconHeight)
            && directionY > 0)
            directionY = -1;
        else if (y <= 0 && directionY < 0)
            directionY = 1;

        // Move
        x += directionX * speed;
        y += directionY * speed;

There are three parts to the Update. The first is to perform any initialisation: in my case, I focus on the canvas and call the resize event here. This potentially could be done on an event, but you would still have to check inside this loop if it had been done. The second is to stop the player leaving the screen; and finally, we adjust the player position.


As you saw earlier, there are two events that are handled; the first is the user resizing the screen:

function onResizeGameWindow() {
    var canvas = document.getElementById("mainCanvas");
    windowWidth = canvas.width;
    windowHeight = canvas.height;

This basically ensures that the game adjusts to the browser dimensions. This might also be where you would determine if the window was made so small that the game could no longer be played.

The second event was the keydown event. This effectively provides the control for the player:

function onKeyDown(e) {
    if (!e) e = window.event;     

    if (e.keyCode == 39) {
    else if (e.keyCode == 37) {

    if (e.keyCode == 38) {        
    else if (e.keyCode == 40) {        

The top line is because the parameter comes through as null.


If you run this game, you’ll see that you can move the square around the screen, increase and decrease its speed, and stop. Not exactly the next Call Of Duty, I’ll grant you, but the foundation of a game, certainly.