How to include js files in the view. ASP.NET MVC 4 - javascript

I wonder why my js file work when I call it in the view:
#section Scripts {
<script>
function myFunction() {
alert("Hello1");
}
</script>
}
but does not work when I call it:
#section Scripts {
<script type="text/javascript" src="~/Views/Home/script.js"></script>
<script>
myFunction();
</script>
}

It's because .js files are not accessible in the ~/Views/ folder. You have to enable it.
To enable access to .js files in the Views folder, you can add the following to your Views' folder's web.config directly under the handlers tag:
<add name="JavaScriptHandler"
path="*.js"
verb="*"
preCondition="integratedMode"
type="System.Web.StaticFileHandler" />
Alternatively put your script into the ~/Scripts/ folder and reference it like such:
#Scripts.Render("~/Scripts/script.js")

Its better practice to place your Js file in Script folder and access it from there. You could write this code in view's head to use the js file
#Scripts.Render("~/Scripts/script.js")

you have to add your script in the Bundle config :
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js", "~/Views/Home/script.js"));
this worked for me

You should Add rendersection to your Layout Page which your view using.
#RenderSection("scripts", required: false)

Related

Blazor WebAssembly load different scripts for specific Environment

I'm currently working on a .NET Standard 2.1 Blazor WebAssembly application. I try to include or exclude JavaScript files in my index.html according to an environment variable.
The Blazor WebAssembly App is NOT Asp.NET Core hosted.
In .NET Core there are usually Environment Tag Helpers like in the following example:
<environment include="Development">
<script src="js/app.js"></script>
<script src="js/helpers.js"></script>
</environment>
<environment exclude="Development">
<script src="js/site.min.js"></script>
</environment>
As already discussed in this question Blazor WebAssembly Environment Variables, the Environment Tag Helpers are server side code and thus don't work in Blazor WASm.
Now I try to find a good solution to include/exclude JavaScript files according to the Environment variable in Blazor WebAssembly.
The first idea was, similar like for CSS, to create a component called <Scripts> to load the different script files on the index.html like this:
#using Microsoft.AspNetCore.Components.WebAssembly.Hosting
#inject IWebAssemblyHostEnvironment hostEnv
#*Check the environment value*#
#if (hostEnv.IsDevelopment())
{
<script src="js/app.js"></script>
<script src="js/helpers.js"></script>
}
else
{
<script src="js/site.min.js"></script>
}
#code {}
Unfortunately this doesn't work, because the <script> Element is not allowed to be used in a Blazor component (.razor file).
The following error occurs: The script element allows authors to include dynamic script and data blocks in their documents. The element does not represent content for the user. ... Script tags should not be placed inside components because they cannot be updated dynamically. To fix this, move the script tag to the 'index.html' file or another static location. ... https://go.microsoft.com/fwlink/?linkid=872131
How do you load different scripts according to the Environment Variable i.e. Development, Production or Staging in Blazor Webassembly?
Do you know how to solve this problem?
I wanted to add Tailwind CDN script tag just during development. I ended up using the solution below:
index.html
<script src="_framework/blazor.webassembly.js"></script>
<script>
// If localhost, add tailwind CDN (or any other script that you want)
if (window.location.hostname == 'localhost') {
var customScript = document.createElement('script');
customScript.setAttribute('src', 'https://cdn.tailwindcss.com');
document.head.appendChild(customScript);
}
</script>
Simply copy your index.html code in a .cshtml (named BlazorApp.cshtml in the following sample) in your server project and fallback to this page.
public void Configure(IApplicationBuilder app)
{
...
app.UseEndpoints(endpoints =>
{
...
endpoints.MapFallbackToPage("/BlazorApp");
}
}
And update the code with <environment> tags for your conveniance.
Please check the solution in this answer (same question as you linked above) and that seems to work.
Basically the workaround is to use this in a new component called Head.razor as per the solution:
#inject IWebAssemblyHostEnvironment hostEnv
#if (hostEnv.IsDevelopment())
{
<title>BlazorWasmApp - In Debug</title>
<link href="css/debug.css" rel="stylesheet" />
}
else
{
<title>BlazorWasmApp - Not Debug</title>
<link href="css/live.css" rel="stylesheet" />
}
New Head.razor component:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
//Add the Head to root components
builder.RootComponents.Add<Head>("head");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
}

Edit bundle config class for newly implemented theme

When I try to bundle my CSS and javascript, my javascript and CSS effects do not seem to work. I am using the js files and CSS files normally as in ASP.NET Web Forms.
I have kept my CSS and js files only in below code
<link rel="stylesheet" href="~/plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="~/dist/css/adminlte.min.css">
<!-- REQUIRED SCRIPTS -->
<script src="~/plugins/jquery/jquery.min.js"></script>
<script src="~/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="~/dist/js/adminlte.js"></script>
<script src="~/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="~/dist/js/pages/dashboard3.js"></script>
#RenderSection("scripts", required: false)
Here is the bundle config class
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
How can I bundle my js files and CSS files?
Also, I have referenced the jquery validate js file, still validation is not working in my pages. What is the problem?
Please see the attached image for file structure.
This is is how I would do it for your setup.
Make sure you have installed the nuget package Microsoft.AspNet.Web.Optimization.
Here is the edited BundleConfig
public static class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/bundles/allcss")
.Include("~/plugins/fontawesome-free/css/all.min.css")
.Include("~/dist/css/adminlte.min.css"));
bundles.Add(new ScriptBundle("~/bundles/alljs")
.Include("~/plugins/jquery/jquery.min.js")
.Include("~/plugins/bootstrap/js/bootstrap.bundle.min.js")
.Include("~/dist/js/adminlte.js")
.Include("~/plugins/jquery-validation/jquery.validate.min.js")
.Include("~/dist/js/pages/dashboard3.js"));
}
}
The global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
//other unrelated code
}
}
Relevant parts of _Layout.cshtml
Note you don't have to put the Render calls in the _layout.cshtml but this is the standard place for most apps.
#using System.Web.Optimization
<!DOCTYPE html>
<html>
<head>
#Styles.Render("~/bundles/allcss")
</head>
<body>
#Scripts.Render("~/bundles/alljs")
#RenderSection("scripts", required: false)
</body>
I believe you also need to put jquery.validate.unobtrusive.js after jquery.validate.js. Ensure you have added the correct settings in your web.config
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<!--other settings-->
</appSettings>
See this for more explanation

Include static files in a reusable Razor Class Library

I am trying to make a reusable class library (RCL) that I can use in several ASP.NET Core MVC projects. So far so good… until I try to include the required JavaScript in the RCL. There is little-to-no documentation about this topic. My best shot was to try this example.
But when I do, I get the following error when I build the library:
This is the project file and the structure of the library:
Any help is appreciated.
Now that I have some spare time I will answer my own question. Maybe it will useful for someone.
Finally I solved this problem using EmmbededResources without the EmbeddedFilesManifest as ianbusko pointed out in Github.
First I created an extension for the IApplicationBuilder class:
namespace Dashboard.Lib.Extensions
{
public static class IApplicationBuilderExtension
{
public static void UseDashboardScripts(this IApplicationBuilder builder)
{
var embeddedProvider = new EmbeddedFileProvider(typeof(Areas.Dashboard.ViewComponents.DashboardViewComponent)
.GetTypeInfo().Assembly, "Dashboard.Lib.Scripts");
builder.UseStaticFiles(new StaticFileOptions()
{
FileProvider = embeddedProvider,
RequestPath = new PathString("/Scripts")
});
}
}
}
Then I added the javascript files to the project file:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<GenerateEmbeddedFilesManifest>false</GenerateEmbeddedFilesManifest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="2.1.1" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Scripts/**/**/**/*" Pack="true" />
</ItemGroup>
In the RCL view the javascript is included as follows:
#section Scripts{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript" src="~/Scripts/pagination.js"></script>
<script type="text/javascript" src="~/Scripts/checkdigit-validator.js"></script>
<script type="text/javascript" src="~/Scripts/rut-validation.js"></script>
}
Finally in the Statup.cs in the main MVC project you just have to include the following:
app.UseStaticFiles();
app.UseDashboardScripts();

Loading seperate javascript for different views in MVC

I have 3 views in my MVC5 App. Say A,B,C and 3 javascript files A.js, B.js C.js
When appropriate view is loaded, I want appropriate javascript files to get loaded. I do not want all files to get loaded at the start up.
How do I achieve that?
In ViewA, add the following
#scripts {
<script src="A.js"></script>
}
In ViewB, add the following
#scripts {
<script src="B.js"></script>
}
and so on...
If you are using a _Layout.cshtml, make sure you have the proper RenderSection:
#RenderSection("scripts", required: false)
then in the views itself do this:
#section scripts {
<script src="B.js"></script>
}

Unload/Remove javascript functions from ASP.NET MVC partial view

In a partial view I load a javascript file like this :
<script src="#Url.Content("~/Scripts/Testing.js")" type="text/javascript"></script>
In the Testing.js, there are some functons defined
That's work, the functions defined in the file can be used.
Now I do an action in my application, my controller return an another (where I don't load any js file) partial view. The functions defined in Testing.js are still available in this partial view.
Is there a way to "remove" the functions loaded in the first view ?
Thanks,
Update 1
I tried this in the partial view but error :
The file "~/Views/xxxx.cshtml" cannot be requested directly because it calls the "RenderSection" method.
#section MyScript {
<script src="#Url.Content("~/Scripts/Testing.js")" type="text/javascript"></script>
}
#RenderSection("MyScript", false)
You should avoid referencing any scripts in partials. You could define a section in your Layout, for example just before the closing </body> which will allow for views to include some custom scripts:
<script type="text/javascript" src="#Url.Content("~/scripts/some_common_script_that_will_be_used_by_all_views_such_as_jquery_for_example")"></script>
#RenderSection("scripts", false)
</body>
</html>
and then in the view (not in the partial view) override this section to include any scripts that this view might need:
#section scripts {
<script src="#Url.Content("~/Scripts/Testing.js")" type="text/javascript"></script>
}

Categories

Resources