Click here to Skip to main content
13,831,444 members
Click here to Skip to main content
Add your own
alternative version

Stats

8.7K views
8 bookmarked
Posted 12 Dec 2018
Licenced CPOL

Simple ASP.NET CORE 2.2 App +Vue JS

, 13 Dec 2018
Rate this:
Please Sign up or sign in to vote.
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.

Select ASPMVC Project Template:

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

Add -> Add Client-side library...

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.

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.

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:

@{
    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).

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.

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:

Add a reference to axios on Index.cshtml:

@{
    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:

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)

Share

About the Author

jicking
Software Developer
Philippines Philippines
I make art(games) for fun and write code for food.
I personally believe that DotNet Core is the future.

You may also be interested in...

Comments and Discussions

 
QuestionNice Pin
rjs12343116-Dec-18 21:00
memberrjs12343116-Dec-18 21:00 
QuestionHow can I contact you? Pin
Jon198716-Dec-18 18:59
memberJon198716-Dec-18 18:59 
GeneralMy vote of 5 Pin
teedor14-Dec-18 7:13
memberteedor14-Dec-18 7: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190114.1 | Last Updated 14 Dec 2018
Article Copyright 2018 by jicking
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid