user7404066
user7404066

Reputation:

Add JavaScript files in asp.net mvc

I am new in asp.net mvc and I am trying to include .js files in my project but I could not access it on my browser. Like it.

@Scripts.Render("~/bundles/responds.js")
@Scripts.Render("~/bundles/jquery-1.11.3.min.js")
@Scripts.Render("~/bundles/jssor.slider-22.0.15.mini.js")
<script type="text/javascript">
</script>

Anyone can help me, how can I add these files in mvc project? These files exists in Scripts folder.

Upvotes: 9

Views: 26112

Answers (3)

Amin Karimi
Amin Karimi

Reputation: 1

You can use C# code to calculate & generate the right file address as follows:

<script type="text/javascript" src='@Url.Content("~/Content/vendor/jquery/jquery.min.js")'></script>

This pattern can use in *.cshtml files.

Upvotes: 0

user7404066
user7404066

Reputation:

I have solved my problem by just drag and drop script files from Scripts folder to at desired place in Index.cshtml and Visual studio auto generate below code.

<script src="~/Scripts/jquery-1.11.3.min.js"></script>
<script src="~/Scripts/jssor.slider-22.1.5.mini.js"></script>

Which includes the script files in asp.net MVC.

Upvotes: 7

MathijsDr
MathijsDr

Reputation: 131

You can manually add a .js file to a view with the following example code

@model YourNameSpace.ViewModels.YourViewModel
@Scripts.Render("~/Scripts/yourScript.js")

If you want the files to be bundled & you can add them in App_Start/BundleConfig.cs

Example:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle(("~/bundles/customBundle").Include(
     "~/Scripts/yourScript.js", 
     "~/Scripts/anotherScript.js");
}

You can render your script files for the whole application in the ~/Views/Shared/_Layout.cshtml file or any master page by adding the following code

@Scripts.Render("~/bundles/customBundle")

You can inspect the .js file by browsing to the root of your application & add the path of the .js file or bundle (for this example)

http://localhost:9654/bundles/customBundle
http://localhost:9654/Scripts/yourScript.js

Upvotes: 13

Related Questions