Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use @Scripts.Render with .Net Core 2.0 MVC application?

How can I use @Scripts.Render with a .NET Core 2.0 MVC application?

I am converting code from .NET Framework 4.6.1 to .NET Core 2.0. I have read from here how to bundle with .NET Core 2.0. How can I fix the error, and replace the code with the new version?

Code:

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

It says

The name 'Scripts' does not exist in the current context

Existing BundleConfig.cs:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Scripts/jquery-{version}.js"));
    bundles.Add(new ScriptBundle("~/bundles/jqueryvalidate").Include(
    BundleTable.EnableOptimizations = true;
}
like image 343
Sajeetharan Avatar asked Jan 24 '18 05:01

Sajeetharan


People also ask

How can you include scripts in an MVC application?

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.

Where do I put script render?

I would also advise you to put your @Scripts. Render before the closing tag of the page body.

What is the use of scripts render?

Render generates multiple script tags for each item in the bundle EnableOptimizations is set to false. When optimizations are enabled, Render generates a single script tag to a version-stamped URL which represents the entire bundle.


2 Answers

In ASP.Net MVC Core they removed BundleConfig.cs and replaced with bundleconfig.json file. you need to specify your bundle and minification logic in bundleconfig.json. If you don't have this file in your project add json file with this name.

bundleconfig.json

Content of this file should like below.

  // Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/bundles.min.js",
    "inputFiles": [
      "wwwroot/js/site.js",
      "wwwroot/lib/jquery/dist/jquery.js",
      "wwwroot/lib/jquery/dist/jqueryvalidate.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

_Layout.cshtml

 <script src="~/js/bundles.min.js"></script>

Read Microsoft docs related to Bundling and minification to get more understanding about Bundling and minification in asp.net core mvc

like image 100
Ahamed Ishak Avatar answered Oct 20 '22 00:10

Ahamed Ishak


As stated in the other answer, the BundleConfig.cs is gone. However, the @Scripts.Render() had some good use cases and it's not a good idea to replace it with static <script src="..."></script>. In some cases where you only want to link libraries on some pages, not all, you don't want to repeat the same code over and over especially when you link to the libraries in CDNs with fallbacks. So here is a good approach that I use to replace the old good @Scripts.Render():

First create a partial view for your libraries. You can combine the ones that you use together in the same view if you like. Think about it like you're creating bundles in BundleConfig.cs. For example, you can create a view for the jQuery validation like this:

<environment include="Development">
    <script src="~/lib/jquery-validate/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.19.0/jquery.validate.min.js"
            asp-fallback-src="~/lib/jquery-validate/jquery.validate.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator"
            crossorigin="anonymous"
            integrity="sha384-jR1IKAba71QSQwPRf3TY+RAEovSBBqf4Hyp7Txom+SfpO0RCZPgXbINV+5ncw+Ph">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.10/jquery.validate.unobtrusive.min.js"
            asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
            crossorigin="anonymous"
            integrity="sha384-y9k3BO+hbWD6gTgtfMyg1egwFmd2oEgQ0fALVtFnCl9F6j6mCh+oCa0P0h+aj7Ii">
    </script>
</environment>

You can call it something like _ValidationScriptsPartial.cshtml.

Now, on the pages where you need the validation, you can inject the partial view like this:

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

Of course, for those libraries that are required on all pages (like jQuery and Bootstrap), you can inject them directly in _Layout.cshtml like this:

<!DOCTYPE html>
<html>
<head>
    ...
    @await Html.PartialAsync("_LayoutHeadScriptsPartial")
</head>
<body>
    ...
    @RenderBody()
    ...
    @await Html.PartialAsync("_LayoutFooterScriptsPartial")
    @RenderSection("scripts", required: false)
</body>
</html>
like image 42
Racil Hilan Avatar answered Oct 19 '22 22:10

Racil Hilan