Add custom script files to MVC project

How to add custom script files to your project.

Writing inline javascripts is not a good practice when it comes to larger projects and its always recommend to use separate scripts files(custom script file (s)) for bigger scripts.

Adding a custom script is not much complicated in ASP.NET MVC but still we have to follow some steps to accomplish this task.

First add a folder called “custom” or whatever the name you want and add a .js file inside that folder.

custom script

Now we have to register that custom folder and the custom script file. So we need to go to the “BundleConfig.cs” file inside the “App_Start” folder.

In bundleconfig file we can see all the registered script bundles and style bundles. Register the new script as a bundle inside the “RegisterBundles” method. If we need to add more custom javascript files later, we can register them under this custom bundle.

After that we have to tell the Razor engine to render this custom bundle into all the pages, so we have to add this to the “Layout” view or any other master views.

Go to Views -> Shared -> _Layout.cshtml file and add the render code.

Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.

Ok. We are done with the registration. Now we have to check whether its working or not. So add a button on home page.

Go to Views -> Home ->Index.cshtml and add a button

<input type=”button” value=”Click me” id=”hellobtn” class=”btn btn-danger”/>

now we can catch the button click event and show an alert message.

in our custom js file add the button click event.

When you click on the newly added button, you can see the alert message.




6 thoughts on “Add custom script files to MVC project

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.