ASP.NET WebForms Routing Javascript Error - javascript

I have some problems with JavaScript using ASP.NET 4.0 WebForms Routing.
My code:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("GoodInfo", "catalog/good/{good}", "~/GoodInfo.aspx");
routes.MapPageRoute("GoodGroup", "catalog/group/{group}", "~/default.aspx");
}
With no routing everything is ok. But when I use it I got an error on hte page (in Firebug)
Error: jQuery is not defined
on this line:
jQuery(document).ready(function () {
HideBlocks();
});
So my JavaScript does not work on the page that was routed.
I added this line routes.Ignore("{resource}.axd/{*pathInfo}"); but it didn't helped me.

I have solved my problem! The solution consists of 2 parts.
Firstly I changed my scripts definition from
<script type="text/javascript" src="../scripts/something.js"></script>
to
<script type="text/javascript" src="/../scripts/something.js"></script>
Thanks MilkyWayJoe fot that solution.
Secondly I added Ignore Routing
routes.Ignore("catalog/good/{resource}.axd/{*pathInfo}");
instead of:
routes.Ignore("{resource}.axd/{*pathInfo}");
So my web resources have no more routes on pages like http://mysite.com/catalog/good/41
Also I have script events on the page like http://mysite.com/catalog/good/41/event/seq/1. To catch all parameters I add to my route rules this
routes.Ignore("catalog/good/{good}/{*query1}");
routes.Ignore("catalog/good/{good}/{query1}/{*query2}");
routes.Ignore("catalog/good/{good}/{query1}/{query2}/{*query3}");
routes.Ignore("catalog/good/{good}/{query1}/{query2}/{query3}/{*query4}");
And don't forget that your Ignore declarations must be placed before MapPageRoute declarations:
routes.Ignore("catalog/good/{resource}.axd/{*pathInfo}");
routes.MapPageRoute("GoodInfo", "catalog/good/{good}", "~/GoodInfo.aspx");`enter code here`

If you look at the generated source of your page, is the jQuery library included?
If you are including jQuery via a resource, double check that it is included and that it is before that line that errors.

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();
}

How and where to add JQuery in Module project in DotnetNuke(DNN)?

I am beginner in DotnetNuke. I am creating a project which provide a Module that can be add in DotnetNuke based website.
I have configured www.dnndev.me in my IIS server and created project in DesktopModule folder of it. I can create, build and add my module to www.dnndev.me successfully but I don't know where to add JQuery in Solution Explorer of my module project.
1- Where should I add my JS and CSS files? I have tried by adding a folders "Assets", "Assets/CSS", "Assets/JS" and put my files there in my solution explorer.
2- How to include JS/CSS files in ascx page?
I have tired by following
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="View.ascx.cs" Inherits="CustomerDemo.Modules.CustomerDemo.View" %>
<dnn:DnnCssInclude runat="server" FilePath="~/DesktopModules/CustomerDemo/Assets/JS/fullcalendar.min.js" />
<dnn:DnnCssInclude runat="server" FilePath="~/DesktopModules/CustomerDemo/Assets/JS/jquery-ui-timepicker-addon.js" />
By above way .js shows in my source of webpage but it doesn't call. But if I try by following way, it works
<script type="text/javascript">
$(document).ready(function () { $.getScript("http://www.dnndev.me/DesktopModules/CustomerDemo/Assets/JS//jquery-ui-timepicker-addon.js?_=1483026285109", function () {
if ($('.mmdd').length > 0) {
$(".mmdd ").datetimepicker();
}
});
});
</script>
Can anybody please suggest me how and where to place .js and '.css' files and how to include them in project?
I am using: Visual Studio 2015 & DotnetNuke 8 Commnunity
File path confusion:
This is my physical location of folder when I open by Right Click--> Open with folder explorer
F:\websites\dnndev.me\DesktopModules\CustomerDemo\CustomerDemo\Assets
But when I drag CSS or JS file from file explorer to ascx design page, it use this location: "~\DesktopModules\CustomerDemo\Assets\file.css"
you can see that the physical path has 2 folder of CustomerDemo and the file dragged from solution explorer having path with only 1 CustomerDemo folder.
I don't understand this mechanism. Which one should I use? Can somebody clear my mind for this?
I have tried this way as one of the suggestion but it looks like I am missing something
Use the DnnJsInclude control of the Client Resource Management for registering scripts instead of the DnnCssInclude.
In your .ascx:
<%# Register TagPrefix="dnn" Namespace="DotNetNuke.Web.Client.ClientResourceManagement" Assembly="DotNetNuke.Web.Client" %>
<dnn:DnnJsInclude runat="server" FilePath="~/DesktopModules/CustomerDemo/Assets/JS/fullcalendar.min.js" />
OR in your code behind, you could instead use the ClientResourceManager API:
protected void Page_PreRender(object sender, EventArgs e)
{
ClientResourceManager.RegisterScript(this.Page, base.ControlPath + "/Assets/JS/fullcalendar.min.js", 100);
ClientResourceManager.RegisterScript(this.Page, base.ControlPath + "/Assets/JS/jquery-ui-timepicker-addon.js", 100);
ClientResourceManager.RegisterStyleSheet(this.Page, base.ControlPath + "/Assets/CSS/module.css", 100);
}

How to give dynamic query parameter in <script> src?

I am building a simple asp.net application and in my aspx page I want to reference a script with dynamic query parameter.
For example:
<script src="../javascript/script.js?v=#var#" type="text/javascript"></script>
In the above code script path can have different query parameter in place of #var#.
I have also tried following code to get the parameter value from code behind.
<script src="../javascript/script.js?v=<%# myVar %>" type="text/javascript"></script>
but, here <%# myVar %> returns blank value. If I use = instead of # then it works perfectly if I add the script reference at the bottom of the page.
But, it only works if I reference the script at the bottom of page. otherwise it will throw the error.
"The Controls collection cannot be modified because the control contains code blocks (i.e. `<%= %>`)."
Now, my question is, "Is there any other way to do the same?"
I am assuming you are using ASP.net not MVC. I have tried this with ASP.net and done this by code behind approach you can create your script tag by code behind like below:
protected void Page_Load(object sender, EventArgs e) {
string jScriptValidator;
jScriptValidator = "<script type='text/javascript' src='../javascript/script.js?v=#123'></script>"; // your dynamic script tag with dynamic parameter
Page.RegisterStartupScript("key", jScriptValidator);
}
and result is follows:
Hope it helps you.

Play Framework template that is actually a JS file

I'd like to have a Play template that is a JS file (as opposed to having <script> tags inside an HTML template). The reason for this is so that the script can be cached. However, I need to create a differences in the script depending on where it's included and hoped to do this with Play's template system. I can already do so if I use embedded scripts, but those can't be cached.
I found an existing question that also asks the same thing, but the answer is totally different (different goals).
That's easy, just... create view with .js extension, i.e.: views/myDynamicScript.scala.js:
#(message: String)
alert('#message');
//Rest of your javascript...
So you can render it with Scala action as:
def myDynamicScript = Action {
Ok(views.js.myDynamicScript.render(Hello Scala!")).as("text/javascript utf-8")
}
or with Java action:
public static Result myDynamicScript() {
return ok(views.js.myDynamicScript.render("Hello Java!"));
}
Create the route to you action (probably you'll want to add some params to it):
GET /my-dynamic-script.js controllers.Application.myDynamicScript()
So you can include it in HTML templite, just like:
<script type='text/javascript' src='#routes.Application.myDynamicScript()'></script>
Optionally:
You can also render the script into your HTML doc, ie by placing this in your <head>...</head> section:
<script type='text/javascript'>
#Html(views.js.myDynamicScript.render("Find me in the head section of HTML doc!").toString())
</script>
Edit: #See also samples for other templates types

How can I use the script defer attribute for ASP MVC 4 Bundles with Scripts.Render

I have looked through Google and Stackoverflow and haven't found an answer for this. Is there any built in way to make a bundle execute as deffered or does someone know of an extension helper method that someone wrote to do this?
Try upgrading the Web Optimization to version 1.1.0 on
Codeplex Site or via Nuget Package
In version 1.1.0 they included Element Template Strings.
So if you want a script tag to contains the defer attribute you can easily do this:
#Scripts.RenderFormat("<script src='{0}' defer></script>","~/bundles/jquery")
and the following markup will be generated:
<script src="/Scripts/jquery-1.7.1.js" defer></script>
The answer above is great. I just want to quickly paste my code over here for those who wants to have a more concise syntax.
Add a new C# class
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Scripts7.cs" company="Believe">
// http://believeblog.azurewebsites.net/
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Web;
using System.Web.Optimization;
namespace MVCExtension
{
/// <summary>
/// The scripts.
/// </summary>
public static class Scripts
{
/// <summary>
/// Render scripts as deferred
/// </summary>
/// <param name="paths">
/// The paths.
/// </param>
/// <returns>
/// The <see cref="IHtmlString"/>.
/// </returns>
public static IHtmlString RenderDefer(params string[] paths)
{
return Scripts.RenderFormat(#"<script src='{0}' defer></script>", paths);
}
}
}
Then, use Razor syntax:
#Scripts.RenderDefer("~/bundles/jquery")
Or Webform syntax:
<%: Scripts.RenderDefer("~/bundles/jquery") %>
You can use BundleTable.Bundles.ResolveBundleUrl :
<script src="#(BundleTable.Bundles.ResolveBundleUrl("~/bundles/jquery"))" defer></script>
Late answer but I would like to add because I am across almost similar problem where I need to add a data attribute to the bundled scripts (in relation with a GDPR cookie solution).
The solution CookieBot was blocking some of the scripts on Auto-Mode, therefore, I need to implement in Manual mode and mark all of my scripts to be ignored by CookieBot script.
My scripts in BungleConfig.cs looks like this:
bundles.Add(new StyleBundle("~/Bundles/late").Include(
"~/Scripts/jquery.pep.js",
"~/Scripts/jQuery.easing.1.3.js",
"~/Content/swiper/js/swiper.js",
"~/Scripts/uiActions.js",
"~/Scripts/xxm.js",
"~/Scripts/addtohomescreen.js",
"~/Scripts/d3.min.js"
));
And, in my _Layout.csthml.
#Scripts.RenderFormat("<script data-cookieconsent='ignore' src='{0}' > </script>", "~/Bundles/late")
And, this is what I got after being rendered.
<script data-cookieconsent="ignore" src="/nyhed/Bundles/late?v=k3Zae8tC12ZNx0x1iAhyu4U0c8xmGE5TrdLdAqg9C8M1"> </script>
Now, the original question, one can add defer or async along with or without data attribute.
Scripts.Render and scripts.RenderFormat both are referenced to System.Web.Optimization, and should be already availabe on MVC project.

Categories

Resources