58

I need to integrate Vue.js with some ASP.NET Core MVC views. I picked Vue.js over other alternatives because it seemed to be simpler – "just add it via a <script> tag", they said. No need to learn Gulp/Grunt/Webpack/Browserify/etc.

That turned out to be false. At my first attempt to handle dates I tried some extensions like vue-moment and vue-datetime-picker, taken from this official curated list of awesome things related to Vue.js but I hit a wall here. While the first does not mandate using the require() JS syntax (CommonJS?), the second one doesn't work without it. Other extensions happen to 'use babel' and imports/exports which is ECMAScript 6 that needs to be compiled. So, most Vue.js libraries and toolings indeed need a compiler, plus the require() syntax, and all that stuff from the Node world?

How should I set up my project to work with ASP.NET Core MVC + Vue.js, in a way that I can develop many small Vue apps using Vue plugins (that can require(stuff))?

4
  • 1
    Turns out that vue-moment failing on non-compliled environnements is actually a bug. - stackoverflow.com/q/39601389/97471 Sep 21, 2016 at 0:05
  • I tried ASP.NET Core Template Pack. But I don't get it. Is it just a vue-webpack-boilerplate hosted on kestrel ? Sep 22, 2016 at 6:40
  • 4
    Aspnetcore & Vue (ES6) template here for those looking for it: github.com/MarkPieszak/aspnetcore-Vue-starter Sep 6, 2017 at 13:37
  • I know that this topic is quite old but I found it searching how to do. In 2018, a modern solution is to execute the following command: npx vue-cli-service build --mode development --dest ../2-BackEnd/wwwroot/ --watch npx here allow to start the vue-cli-service that will build the vue js app, in development mode, and by specifying the destination and with the watch you get everything that you want except the serve. Then you just have to run your .NET app, that will just display what inside wwwroot.
    – Adavo
    Nov 14, 2018 at 7:41

12 Answers 12

76

I was totally lost when I asked the above question. I’ve spent a few days and I still don’t have a complete picture. What I am pretty sure is that 2016 is a hard year to learn JavaScript.

I wanted to use Vue.js because it’s simpler than the alternatives. Less ceremony, fewer boilerplates, less code. It's branded as the Progressive Framework... Right! But only to a point. Vue.js does not solve the JavaScript ecosystem fragmentation problem with build systems.

So, you will have to pick a side: Do you need JavaScript modules and a build system?

Option 1: Keep it simple: Avoid JS modules and build systems.

Reasons to follow this path:

  • You don’t have many days to learn A LOT of stuff. (Configuring bundler, npm+package dependencies hell, ES6 stuff.)
  • You do not want to make a bleeding-edge single-page application. Embedding Vue.js inside a few HTML pages seems enough.
  • HTTP/2 is becoming mainstream, so bundlers like Webpack or Browserify will provide fewer benefits, at least on performance.
  • Eventually ES6 modules will be supported directly in the browser, so we won’t need to build whatever the latest JavaScript is into browser-compatible JavaScript.

You will save many days by not spending time learning stuff that will probably be obsolete in a few years.

If you follow this path, a few recommendations:

  • Just add JS libraries using the <script> tag.
  • Only use browser-ready JavaScript libraries. Code that uses require() or the UMD prefix (function (root, factory) { requires you set up modules (therefore it is not browser-ready unless you set up CommonJS). JS files with import/export statements are written in ES6 so avoid them too.
  • Use Bower to download browser-ready libs. Avoid NPM (which implies having a module system in place).

Caveat: You will not be able to use advanced Vue.js features like single-file components or Vue Router, but that is OK. You will have to do a few things manually.

Option 2: Learn JavaScript modules + build systems.

Prepare a few days to learn and not code. I will only explain briefly how Webpack worked for me. Browserify also works, but I haven't tried it.

I recommend you spend some time learning what JavaScript modules are. Then learn to build them and pack them: I used Webpack. Its documentation is not great, so what worked for me was to follow its tutorial step by step.

At this point, you may have heard that Webpack ALSO has a built-in web server with "hot module reloading". This is a web server for static files to be used only for development. Its benefit is that whenever you edit a JS module, the browser will automatically apply the change without refreshing. This is a very nice, but optional, feature. The problem: this built-in web-server competes with our web server (Kestrel). So, if you want to try this feature during development use the Webpack ASP.NET Core middleware provided at Microsoft’s JavaScriptServices repo. There you will find the WebApplicationBasic template that I am currently using. I dissected it, removed most of its parts and by trying to use it I slowly understood what each part was originally for.

When using Webpack you will mostly use 3 workflows:

  • Built-in development mode: Creates huge files, easy for debugging. Use it together with ‘watch-mode’ so whenever you modify a file, a new Webpack build is triggered.
  • Built-in production mode: Creates small minified files. Useful for ‘dotnet publish’.
  • Using Webpack's web server and hot module reloading with the Webpack ASP.NET Core middleware means your app will run Webpack in the background, build, and watch the source files for changes. The compilation output is not written to disk and only kept in memory and served via HTTP. The JavaScriptServices middleware forwards requests from Kestrel to Webpack's web server to make this work.

Whatever Webpack config you go with, you have to include ‘vue-loader’ in your Webpack config. You may be inspired by Vue’s webpack-simple template.

I haven’t covered everything that I wanted to, but this topic is too extensive and I need to go back to coding. Please leave some feedback.

4
  • Great answer ! Do you know any simple template link with Vue js + Webpack + Laravel or VueJs + Browserify + Laravel instead of Asp.net core ?
    – Rasel
    Nov 22, 2016 at 13:26
  • 1
    I really feel with you. I've been told to make Vue work under our Core app and it went well until I had to add routing. After that, I was totally lost. Would you have time to shed some more light on how to make the routing work for Vue under DotNet.Core? We don't run NodeJs but I might be able to execute gulpfile.json manually every now and then. Nov 27, 2016 at 8:01
  • Hi @Rasel . I haven't used Laravel. Maybe you can search on LaraCasts.com that have a lot of info. laracasts.com/index/webpack Nov 28, 2016 at 16:46
  • @KonradViltersten There is a great guide here: liquidlight.co.uk/blog/article/… Nov 28, 2016 at 17:01
21

I'm late to the party but there is now a template available for .NET Core that you can build with a single command. On a Windows box with .NET Core installed just create an empty folder and in that folder run this command to show a list of available templates:

dotnet new

If you don't have all the templates, you just need to run this to install the SPA templates:

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

And this to scaffold a new Vue app:

dotnet new vue

In milliseconds a complete new Vue.js single-page web app is built with a working .NET Core back end with controllers, views etc. It's brilliant. Just open the project in VS or VS Code and you're away.

There are also templates for Aurelia, Angular, Knockout and React! You can build them all and compare how each solves the same problem. The Angular one even does server side pre-rendering out of the box!

I know .NET Core has a way to go but it's becoming more and more awesome by the day!

8
  • 1
    Great news that they are adding support for vue and thanks for posting! On a new Windows with VS2017 the dotnet new does not have vue as an option. It must be installed via dotnet new --install Microsoft.AspNetCore.SpaTemplates::* May 23, 2017 at 1:01
  • I noticed this template uses TypeScript and I don't know the language. Another thing to learn? :( May 23, 2017 at 1:06
  • Ah yes, thanks for mentioning that you need to install the templates first! Yeah, of course you don't have to use TS but I think it makes sense. May 23, 2017 at 19:00
  • Why does typescript make more sense? Just curious Aug 31, 2017 at 18:34
  • Because you can take advantage of features in TS that make coding in JS easier and safer. You can also use the newer JS features but still compile to es5 and support older browsers. But of course there are plenty of people around who will tell you TS is a bad idea but it won't be the Angular 2+ team. Sep 1, 2017 at 19:03
10

First, a disclaimer: I couldn't find anything that really fit what I needed, so I put together a solution from scratch. See the end.

You ask about including Vue via the <script> tag (in that case the CDN build). However, you also mention using Babel and the ES6 modules feature. In that case I would recommend using Webpack for the client-side app, which will compile your ES6 with Babel, allow you to use modules and components, and work with a template! You also get hot module reloading (edit your source and see changes in the client app in real time!) and Webpack will bundle your SPA into a static HTML5 app.

The official Vue.js docs point to their own Webpack template.

So you can run the Webpack dev server and your ASP.NET Core app independently, if that suits your needs, but there's a better solution that makes development even more streamlined:

Microsoft's open-source JavaScriptServices lets you execute Node.js from ASP.NET Core, and they have some Webpack middleware that integrates the Webpack dev server into your app during debug builds.

They provide official templates for Angular 2, and even a template labeled Vue.js, but the Vue template is just the official Webpack template without any integration with .NET; this is just like the standalone server.

I couldn't find any templates that did this for Vue.js, so I put together a sample ASP.NET Core application that loads the Webpack dev middleware with a Vue.js Webpack app. When the .NET Core server is running in dev mode, you can edit the Vue source, and the changes will be reflected with quick incremental patches without needing to rebuild the entire application. In release mode, .NET Core will use the prebuilt Webpack output. You can find it on GitHub:

https://github.com/0xFireball/YetAnotherShrinker

The repository linked above has a full application demo that uses NancyFx, axios, Vue.js, and Vue Material, and is a simple URL shortener. If you want steps for a more minimal setup that can easily be added to an existing app, check out this blog post of mine.

Obligatory disclosure: I wrote that blog post.

2
  • 1
    Your blog post links (including from the git repo) are all dead as of this writing.
    – k3davis
    Jul 18, 2017 at 11:18
  • 2
    I just updated the post with new links; they should all be good now.
    – 839829389A
    Jul 19, 2017 at 17:36
5

Maybe someone will find this information helpful.

Here are some starter templates you can use for a quick project setup.

The first one gives you a multi-project solution with some predefined architecture. This template more closely matches real-world projects than the JavaScriptServices solution which was already mentioned here. It provides a domain layer, repository layer, etc. Note that this is a Yeoman generator and it uses TypeScript. https://github.com/vue-typed/generator-vue-net-core

The second is just a project on GitHub and you should clone it if you want to use it. It is not a Yeoman generator and I think this is regrettable, but I found the structure in this template better than in the first one. Also, it has a lot of nice little things like some exception filters, that you, most likely, will still do anyway. And if you are a beginner, this template will be just a godsend. This template is recommended on the awesome-vue page. Here's the link: https://github.com/mrellipse/toucan

4

I found a way to create single file Vue Components in ASP.NET Core Web App by storing them as shared Razor Views and referencing as Partials in the project. This way does not require using of any JavaScript Bundles It is a very simple solution and works perfectly with Vue v2.6.x.

Here is a simple single file Bootstrap Card Vue component (_Card.cshtml).

<style>
    .card {
        width: 15rem;
    }
</style>
<script type="text/javascript">
    Vue.component('vue-card', {
        props: {
            id: String,
            name: String,
            img: String
        },
        template: '#vue-card-template'
    });
</script>
<script type="text/template" id="vue-card-template">
    <div v-bind:id="id" v-bind:name="name">
        <div class="card">
            <img v-bind:src="img" class="card-img-top p-4 bg-light border-bottom">
            <div class="card-body">
                <p class="card-text">
                    <slot></slot>
                </p>
            </div>
        </div>
    </div>
</script>

And this is the part using it on a Razor Page:

<div id="app">
    <vue-card id="Id" name="Card" img="https://vuejs.org/images/logo.png" class="mb-4">
         <h6>Bootstrap 4 Card Vue Component</h6>
       </vue-card>
</div>

@section Scripts {

<partial name="_Card" />

<script type="text/javascript">
        var app = new Vue({
            el: '#app'
        })
</script>
}

Please check my sample project on Github for details: ASP.NET Core + Vue.js

I also wrote an article about my way of Using Vue Components in ASP.NET Core at Medium.

3

I created this template that combines .NET MVC with Vue.js. You can use the entire Vue ecosystem but if you don't want it on any page you can just opt out.

GitHub: https://github.com/danijelh/aspnetcore-vue-typescript-template

Medium: https://medium.com/@danijelhdev/multi-page-net-core-with-vue-js-typescript-vuex-vue-router-bulma-sass-and-webpack-4-efc7de83fea4

You can use it as an example or starting point.

3

You can try the steps below, from this simple guide.

  1. Set up the npm configuration file (package.json)

Below is the npm package I will use:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "laravel-elixir": "^6.0.0-14",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "vue": "^2.0.1",
    "vue-resource": "^1.0.3",
    "vuex": "^2.1.1"
  }
}
  1. Install the npm package

Open a command prompt and go to the root folder of your application and install the npm packages set from your package.json file using the command ‘npm install’, without the quotes.

  1. Set up Gulp

Once the npm package is installed you may now set up the Gulp file. You will need to add a Gulp configuration file (gulpfile.js). Later on we will create the Vue JS which we will call vueApp.js with the code below. The first argument is the public output directory and the other one is the source directory. For more details on Webpack click here.

var elixir = require('laravel-elixir');



require('laravel-elixir-vue-2');

elixir(function (mix) {
    mix.webpack('vueApp.js', 'wwwroot/js/dist', 'wwwroot/js');
});
  1. Create the Vue JS file

In your ASP.NET Core web app project solution explorer go to wwwroot and add a ‘js’ folder and if it does not exist then add again a new folder named ‘dist’. Now once the folder setup is complete add a new JavaScript file in the ‘js’ folder named ‘vueApp.js’.

  1. Start coding in your Vue JS file

You may now start coding. In the example below we will be displaying an alert to indicate that Vue.js is running.

import Vue from 'vue'

new Vue(
    {
        el: '#app',
        data() {
            message:'hello world using Vue.js on ASP.NET Core MVC.'
        },
        mounted() {
            console.log(this.message);
        }
    });
  1. Apply Vue JS to your Razor view or HTML

Open your layout page and wrap the content of your body tag with a div and an id of ‘app’. We will use ‘app’ since that is the id tag we used in our sample code from step 5. The name ‘app’ is not required and you may change it to your desired name. Lastly add a reference to the Vue JS file. Be sure to move outside the ‘app’ div the script references to prevent error.

<body>

<div id="app">

    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">Project.Payrole</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                @await Html.PartialAsync("_LoginPartial")
            </div>
        </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2017 - Project.Payrole</p>
        </footer>
    </div>

</div>

<environment names="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
</environment>

<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
            asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
            asp-fallback-test="window.jQuery"
            crossorigin="anonymous"
            integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
            asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
            crossorigin="anonymous"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
    </script>
    <script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>

<script src="~/js/dist/vueApp.js" asp-append-version="true"></script>



    @RenderSection("Scripts", required: false)
</body>
  1. Run Gulp

Now that we have set up the Vue.js configuration and applied it to our Razor view we will need to run Gulp to execute what we have set in our gulpfile. Like in step 2 go to your root folder and open a command prompt then execute the command ‘npm run dev’, again without the quotes.

  1. Run

Now for the final step run your ASP.NET Core MVC app and check the console of your web browser. You should now be able to see the message we set in step 5.

(I wrote the guide in the blog post for reference whenever I may need it :D)

2
  • When copying content, please make sure to follow our attribution guidelines. Please also note that copying whole pages verbatim seldom make good answers; instead, try to post answers which are tailored to the question, and pick and choose snippets from sources where necessary.
    – Matt
    Mar 9, 2017 at 19:51
  • Apologies I have edited the answer, I did write the guide and transfer some here which I think might help on the question.
    – SlowNinja
    Mar 10, 2017 at 3:30
2

I too am late to this party but I believe a lot has changed in the last year or less. Given that the ES6 module spec (and also dynamic modules) now has relatively broad browser support (see CanIUse), the options for integrating Vue.js into ASP.NET MVC Razor views are now far, far better. One thing I've learned about Vue.js is it's best to drop preconceptions about "plug-ins", in the jQuery sense. If you're like me and come from the jQuery world (no Angular or React experience), you must sit down and learn Vue's component model (even SFCs; though you don't need them in this case, they help define the big picture). This requires a decent grasp of ES6 (ECMAScript 2015).

The iterative and incremental approach is, if you want to start learning and leveraging one of Vue's greatest assets (ease of CDD - component driven development), then simply add the "Full" build (see guide) in the script tag. Using ES6 module syntax (import/export) you can build your own library of components that plug in anywhere you need them; no Webpack or transpiling required. This is truly an awesome development because you can dabble in Vue.js, using best practices for componentization, without taking on an initial (onerous) learning curve of adding Webpack and Babel to your .NET project. And, as an added bonus, later on when you need to up your game with modern tooling and workflows (NPM, Webpack, testing, HMR, VS Code, etc), you have many of your components tested and ready to go.

Essentially you build and attach root Vue instances (a.k.a. Vue components) to elements in the DOM. Once you understand that everything is a component then you gain confidence in digging into open-source packages like vue-moment and vue-datetime-picker, and importing them via module syntax or learning from them to incorporate into your own custom components.

2

If you are in 2022 or a bit later, I think, you have to take a look at ServiceStack Project Templates: https://docs.servicestack.net/templates-overview

To install:

dotnet tool install --global x

Or install on Apple's new M1 Pro and M1 Max ARM chips with:

dotnet tool install -g -a x64 x

After that you can check the list of available templates with:

x new

Or simply get your vue + .net core template by:

x new vue-lite-corefx [ProjectName]

0

This question is a bit old but..

I have a little sample project on GitHub that uses ASP.NET and Vue.js. It uses Yarn (or npm) as a package manager and Webpack.

It is not .NET Core, but the way of using it will be the same. It might help you get started.

The strange file structure is because it runs on our Sitecore CMS system.

Hope it helps.

1
  • The project doesn't exist. Can you renew the link? Oct 31, 2022 at 7:49
0

I spent a long time learning how to use Browserify and Babel so I could set up my own ES6 environments. However, when it comes to using Vue I'm quite happy to go with the default templates, which are best accessed by installing Vue-CLI. You can choose between Browserify and Webpack, and either simple setups or full on with linting, unit tests and Single-File Components using the runtime-only version.

It just works.

-1

The best step-by-step tutorial for integrating Vue.js with ASP.NET Core is given here:

https://ourtechroom.com/tech/integrating-vuejs-in-aspnetcore-application/

I have posted here a GitHub sample project:

https://github.com/Diwas777/integrating-vue-with-asp.net-core-project

Not the answer you're looking for? Browse other questions tagged or ask your own question.