Click here to Skip to main content
15,884,388 members
Articles / Web Development / ASP.NET / ASP.NET Core
Tip/Trick

Simple ASP.NET CORE 2.2 App +Vue JS

Rate me:
Please Sign up or sign in to vote.
4.75/5 (12 votes)
13 Dec 2018CPOL3 min read 45.3K   16   6
Set up ASP.NET Core 2.2 app with Vue JS on UI components without using npm/webpack.

Requirement

You got hired by WayKurat, a fictitious company that develops vue js/ ASP.NET Core apps.

The next day, you arrived late at the office. Your boss is waiting for you at your desk, he then cracks a smile when he noticed you approaching. Luckily, he is not mad at you for being late, he is just excited to tell you that he wants you to develop a simple web app from scratch, the app will list down WayKurat Subscribers (the subscription web API is already developed by your annoying colleague).

You are required to use ASP .NET Core 2.2 on VS 2017 and requested to try out libman instead of bower/npm or manually downloading libs.

Solution

Create a new ASP.NET Core application, set project name to WayKuratWeb.SimpleVueJs.

Image 1

Select ASPMVC Project Template:

Image 2

Your boss loves vue js so we will install Vue using Libman. Right click on project, then hit:

Add -> Add Client-side library...

Image 3

Libman adds library window will show up, type in "vue" then click vue (will likely be a different version on your end) on dropdown list. Choose specific files, tick files as is on image below, then hit install.

Image 4

Now that vue is installed, let's make a vue component.
Create a new js file on wwwroot/js/.
Set file name to VueSubscriberListComponent.js (just an example, you can call it like your grandma).

Next, paste this js code. This will be our Vue component.

JavaScript
var subscriberListComponent = new Vue({
    el: '#subscriber-list-component',
    data: {
        subscribers: [],
        isViewReady: false
    },
    methods: {
        refreshData: function () {
            this.isViewReady = false;
            
            //dummy data for now, will update this later
            var subscribers = [
                { name: 'jic', email: 'paytercode@waykurat.com' },
                { name: 'kin', email: 'monsterart@waykurat.com' }
            ];

            this.subscribers = subscribers;
            this.isViewReady = true;
        }
    },
    created: function () {
        this.refreshData();
    }
});

Update project's /Views/Home/Index.cshtml to reference vue and our component:

Razor
@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <div id="subscriber-list-component">
        <h3>WayKurat Subscribers </h3>
        <div v-if="isViewReady == true">
            <ol>
                <li v-for="u in subscribers">
                    {{ u.name }} - {{u.email}}
                </li>
            </ol>
            <button class="btn btn-primary btn-block" 
            v-on:click="refreshData">REFRESH</button>
        </div>
        <div v-else>
            <div>Loading data...</div>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/lib/vue/vue.js"></script>
    <script src="~/js/VueSubscriberListComponent.js"></script>
}

Run app on browser, your app will look like this. If not, check your browser console for errors (please check it before submitting a stackoverflow question, it's not a black box).

Image 5

Now, it is time for us to consume your colleague's web API.
But things are not as they seem to be, he did not push his code yesterday and looks like he is on AWOL.
So you are forced to write a dummy web API for now.

Add a new controller, set name to SubscribersController.cs, then paste this code.

C#
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WayKuratWeb.SimpleVueJs.Controllers
{
    [Route("/api/[controller]/[action]/")]
    public class SubscribersController : Controller
    {
        [HttpGet]
        public IActionResult GetAll()
        {
            //hard coded data for brevity, this must be from a data store on the real world
            var subs = new List<Subscriber>();
            subs.Add(new Subscriber() { Id=1,Name = "JEK",Email="jekhaxor@test.test"});
            subs.Add(new Subscriber() { Id = 1, Name = "Jikie", Email = "jekiedraws@test.test" });
            return Ok(subs);
        }
    }

    public class Subscriber
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

Now that the controller is added, we will be consuming it on our component using Ajax.
You are about to write a plain js sending <span style="color: black"> XMLHttpRequest</span> but your boss smelled it and insisted to use axios.
Well, if that's what he wants, then let's do it.

Install Axios via libman. Open up libman window like how we did while installing vue. Type in "axios", then select files as indicated in the image below:

Image 6

Add a reference to axios on Index.cshtml:

Razor
@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <div id="subscriber-list-component">
        <h3>WayKurat Subscribers </h3>
        <div v-if="isViewReady == true">
            <ol>
                <li v-for="u in subscribers">
                    {{ u.name }} - {{u.email}}
                </li>
            </ol>
            <button class="btn btn-primary btn-block" 
            v-on:click="refreshData">REFRESH</button>
        </div>
        <div v-else>
            <div>Loading data...</div>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/lib/vue/vue.js"></script>
    <script src="~/lib/axios/axios.js"></script>
    <script src="~/js/VueSubscriberListComponent.js"></script>
}

Update VueSubscriberListComponent.js to consume our web API:

JavaScript
var subscriberListComponent = new Vue({
    el: '#subscriber-list-component',
    data() {
        return {
            subscribers: [],
            isViewReady: false
        };
    },
    methods: {
        refreshData: function () {
            var self = this;
            this.isViewReady = false;

            //UPDATED TO GET DATA FROM WEB API
            axios.get('/api/subscribers/getall/')
                .then(function (response) {
                    self.subscribers = response.data;
                    self.isViewReady = true;
                })
                .catch(function (error) {
                    alert("ERROR: " + (error.message|error));
                });
        }
    },
    created: function() {
        this.refreshData();
    }
});

You checked your app on the browser and things run as expected. You did your part, you've pushed your code to repo and prepared for lunch.
Now you've just used libman and written a vue component.
Things will get complicated later but that will be the next post.

External Reference

You'll learn more here:

History

  • 12-13-2018 - Initial post
  • 12-14-2018 - Fixed missing images

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Philippines Philippines
I make art(games) for fun and write code for food.

Comments and Discussions

 
QuestionNeed to reference other components Pin
Member 383949530-May-19 10:58
Member 383949530-May-19 10:58 
QuestionRedirect Pin
Member 101859488-Apr-19 3:01
Member 101859488-Apr-19 3:01 
QuestionWhat can you advise? Pin
VladAndHanna21-Feb-19 4:30
VladAndHanna21-Feb-19 4:30 
QuestionNice Pin
rjs12343116-Dec-18 20:00
rjs12343116-Dec-18 20:00 
Nice work Smile | :) Thumbs Up | :thumbsup:
QuestionHow can I contact you? Pin
Jon198716-Dec-18 17:59
Jon198716-Dec-18 17:59 
GeneralMy vote of 5 Pin
teedor14-Dec-18 6:13
teedor14-Dec-18 6:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.