Zealous System

@zealousys

How to Integrate Vue.JS & Typescript with ASP.NET Core Web Application

Quick Summary: In this tutorial, you’ll learn about Vue.js & Typescript, and how to integrate both with the new ASP.NET Core framework to create a simple web application that performs CRUD (Create, Read, Update, Delete) operations.

A lot has been happening around .NET ecosystem lately. For example, Microsoft has recently released an open-source, cross-platform framework for the first time and named it ASP.NET Core.

For those who don’t know, ASP.NET Core is basically a redesign of ASP.NET MVC framework, built to provide more optimized development environment for creating modern applications.

What is Typescript?

Typescript is an open-source programming language created and maintained by Microsoft. It is designed for building large-scale applications and transcompiles to JavaScript. In a nutshell, Typescript can be used to build JavaScript applications for both client as well as server-side execution.

What is Vue.JS?

Vue.js, on the other hand, is a very popular JavaScript framework used for building user interfaces.

Now before you ask: why would I need to use yet another JavaScript framework when there are already 2 powerful JavaScripts — Angular & React — available?

The truth is, Vue.js is not just another JavaScript in the market. It combines the features of both Angular and React, and is easy to learn and get started.

In fact, Vue.js is experiencing a huge amount of growth right now. According to bestof.js.org, Vue.js added 40K stars last year, making it the number #1 JavaScript framework on Github. Besides, Vue.js can also function as a web app framework with the ability to power advanced single-page applications.

In short…

If you’re not happy with Angular and React, or if you’re in need for less complex and faster option, then Vue.js is worth considering.

Vue.js is a lightweight, high-performance JavaScript framework with virtual DOM implementation. Apart from high-performance, the declarative syntax in Vue.js allows developers to build reactive user interfaces in the easiest way. Plus, it also comes with well-designed components module, allowing you to decide which style works best for you when it comes to mapping your components to files.

And the Best Part?

Vue.js is designed in such a way that it doesn’t end in the view layer. This means, you can adopt its core library and use it for creating your own view layer. And, at the same time, it can also be extended with components and plugins to build even complex Single Page Application (SPA) experiences.

This, in turn, give you the full control of what you exactly require to bring into your project and pick depending on those requirements.

However, if you want to know every single detail in terms of what exactly Vue.JS has to offer and what could you build with Vue.JS, please read the detailed article by its creator, Evan You.

But like I said, if you’re not a big fan of Angular or React and looking to explore other JavaScript options, Vue.JS is the best bet right now. And in this tutorial, I’ll show to how to integrate Vue.JS in your project by creating a simple web application in ASP.NET Core.

Let’s Get Started!

#1 — CREATE A NEW VUE PROJECT USING ASP.NET CORE TEMPLATE:

First we need to Install NPM, Node.js, VS Code and VS 2017.

Then we also need to install the Single Page Application templates provided by Microsoft by using console:

dotnet new — install Microsoft.AspNetCore.SpaTemplates::*

This package will install templates for Vue.

Now to create a new Vue project, run the following commands on the console:

mkdir new-project
cd new-project
dotnet new vue

Next, run npm install on your project root to restore all the required node modules, like webpack and its dependencies.

Lastly, execute dotnet run using console and your application will be run on “localhost:5000” as shown in below screenshot.

As you can see, the client-side app is located in /ClientApp.

This new Project’s Contents are as follow:

• ASP.Net Core backend
• SPA frontend using Vue 2 and TypeScript
• Bootstrap 3 styling
• webpack generating the js/css bundles that are ultimately send to the browser, wired for both development and production modes.

A project structure looks like,

Now, let’s open ClientApp/boot.ts

This is the entry point for our client-side code, the file that contains the code starting the Vue application in the code editor (VS Code):

In this file we can make such a configuration like router configuration, component registration and main Vue application.

#2 — Webpack Configuration

Basically, configuring a single bundle named “main”, to be composed of files starting from ClientApp/boot.ts:

entry: {‘main’: ‘. /ClientApp/boot.ts’},

Now jump to the output property.

Now, to generate the bundles inside the wwwroot/dist folder of the project, use the name of the bundle as the file name:

output: {
 path: path.join(__dirname, bundleOutputDir),
 filename: ‘[name].js’,
 publicPath: ‘/dist/’
},

#3 — Adding a Vue (Template + Typescript) page

Navigate to folder ClientApp/components/Member, and add a new file named members.ts, which will look like following screenshot:

Now add it’s designing template file named member.vue.html

<template>
<div>
<h1>
Member
</h1>
</div>
</template>
<script src=”./member.ts”></script>

Next, we need to add new route in boot.ts adding the following entry to the routes array for accessing this page through navigation:

{ path: ‘/member, component: require(‘./components/member/member.vue.html’) }

Finally, open navmenu.vue.html and add another entry to the menu that renders the /member:

<li>
 <router-link to=”/member”>
 <span class=”glyphicon glyphicon-list-alt”></span> TODO list
 </router-link>
</li>

Here, our basic navigation for newly added page is done via above steps.

Now We need to fetch, insert, delete, update data from database. And for that, we have to call WEB API through axios library which is provided by Vue.

Simply run the command:

npm instal axios –save

Import axios in memebr class. Then get member list from backend api like this way:

getData() {
 axios({
 method: ‘GET’,
 url: ‘https://localhost:44371/api/members/getmembers',
 data: this.memberForm,
 headers: {
 ‘Content-Type’: ‘application/json’
 }
 }).then(response => response.data).then(data => {
 this.memberGridData = data;
 });
 }

Interface on Vue will look like:

interface member {
firstName: string;
lastName: string;
address: string;
gender: number;
occupier: number;
mntncPaidFreq: number;
maintenance: number,
memberId: string;
}

Here, a new project is created with .csproj file which has ASP.Net WebAPI controllers inbuilt, and we can also add the custom controller.

#4 — Create ASP. Net Core Web API using VS 2017

an ASP.NET Core MVC application that performs basic data access using Entity Framework. You will use reverse engineering to create an Entity Framework model based on an existing database.

The following prerequisites are needed to complete this walkthrough:

•Visual Studio 2017 15.3
• Enable IIS from Control Panel
• .NET Core Framework
• .NET Core 2.0 SDK.
• MS SQL Database

Create a new WebAPI Project.

• Open Visual Studio 2017
• File -> New -> Project
• From the left menu select Installed -> Templates -> Visual C# -> Web
• Select the ASP.NET Core Web Application (.NET Core) project template
• Enter Vue-Web-API as the name and click OK
• Wait for the New ASP.NET Core Web Application dialog to appear
• Under ASP.NET Core Templates 2.0 select the Web Application (Model-View-Controller)
• Ensure that Authentication is set to No Authentication
• Click OK

Now, using reverse engineering to create an Entity Framework model based on an existing database.

Open VS 2017 -> Tools > NuGet Package Manager > Package Manager Console

Run Following Command:

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Now create the EF (Entity Framework) model based on your existing database, Run Command:

Scaffold-DbContext “Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

The reverse engineer process created entity classes and a derived context based on the schema of the existing database.

Now we have to move configuration of the database provider to Startup.cs.

Add the following using statements at the start of the file:

using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;

Copy following line to ConfigureServices() method:

var connection = @”Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
 services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

Now that the scaffolding is enabled, we can scaffold a controller for the any entity.

  • Right-click on the Controllers folder in Solution Explorer and select Add -> Controller
  • Select MVC Controller with views using Entity Framework and click Ok
  • Set Model class and Data context class
  • Click Add

It will look like following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SocietyManagement.Models;
using SocietyManagement.ViewModel;
namespace SocietyManagement.Controllers
{
 [Route(“api/[controller]/[action]”)]
 [ApiController]
 public class MembersController : ControllerBase
 {
 private readonly SocietyManagementContext _context;
public MembersController(SocietyManagementContext context)
 {
 _context = context;
 }
// GET: api/Members
 [HttpGet]
 [ActionName(“getmembers”)]
 public IEnumerable<MembersViewModel> GetMembers()
 {
 var listMembers = _context.Members.Include(“FamilyDetail”).Include(“Parking”).Include(“Tenant”).Include(“FlatDetail”).ToList();
 return getMembersViewModel(listMembers);
 }
 }
}

Now, run the application to see it in action.

The Vue Project will look like following after execution:

Member Grid:

Member Add:

Member Edit:

Conclusion

In today’s tutorial, we’ve used Vue.js & Typescript to build an ASP.NET Core web application with CRUD operations. You can find the source code of this demo web application on our Github profile.

More by Zealous System

Topics of interest

More Related Stories