9

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.

6
  • Do you want to add them to a particular view or the entire application? Commented Jan 11, 2017 at 10:39
  • Yes, it is my requirement. Commented Jan 11, 2017 at 10:41
  • In your project you will have a folder named App_Start which will have a file named BundleConfig.cs. Check in there whether you've got the appropriate bundles set. for example @Scripts.Render("~/bundles/responds.js") would be bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/respond.js")); in BundleConfig.cs file Commented Jan 11, 2017 at 10:44
  • 2
    How do you know the scripts aren't included? Do you get 404's? Commented Jan 11, 2017 at 10:56
  • 1
    Yes, when I open it in view page. It gives me 404 error. Commented Jan 11, 2017 at 11:00

3 Answers 3

13

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
Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.