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

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

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 to go up one level in javascript (when using Ajax.open) [duplicate]

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

Sails.js - How to inject a js file to a specific route?

For example, I have a page /locations/map which I need to include Google Map library, and include a .js file (e.g. location.js) specifically for this page only.
I want to inject these 2 files to after <!--SCRIPTS END--> this line
Is it possible to do this?
NOTE: I was using Sails.js v0.10
Sails uses ejs-locals in its view rendering, so you can accomplish what you want with blocks.
In your layout.ejs file, underneath the <!--SCRIPTS END-->, add (for example):
<%- blocks.localScripts %>
Then in the view you're serving at /locations/map, call the block with your script tag, for example:
<% block('localScripts', '<script src="https://maps.googleapis.com/maps/api/js"></script>') %>
As an alternative, you could put the <!--SCRIPTS--> and <!--SCRIPTS END--> tags in the <head> of your layout, and then add your view-specific scripts directly into your view rather than using blocks. This is a fine option if you don't mind waiting for those linked scripts to load before your page content is displayed.
Scott's answer is the proper way to insert non-global JS into a specific view. Just a little comment, though: the block call from the view should not have the dash. It should be as follows:
<% block('localScripts', '<script src="https://maps.googleapis.com/maps/api/js"></script>') %>
Both calls will work, but using the dash makes the insertion twice; once the view is loaded and previous to the layout render, and then once again when the view is inserted in the rendered base layout. This leads not only to inserting/running unnecessarily twice the same code but also to errors that break your JS code if the inserted script depends on libraries that you have in your base layout (e.g. jQuery, Backbone).
EJS interprets the magic <%- as "insert unescaped". So, -I guess- what this is doing is calling the block() function, which returns our HTML <script> tag. This is replaced where the magic was called but also is executing the block() function inside of it, which is executing the layout block localScripts replacement.
On the other hand, <% means "instruction". I.e., just run this JS piece of code, which is not echoed to the view where is called.
I discover other way to do that
In MapController.js
// you can add as many as you like
res.locals.scripts = [
'//maps.googleapis.com/maps/api/js',
];
return res.view();
In layout.ejs
<!--SCRIPTS-->
<!--SCRIPTS END-->
<!-- Loop through all scripts that passed from controller -->
<% if (scripts) { %>
<% for (i = 0; i < scripts.length; i++) { %>
<script src="<%- scripts[i] %>"></script>
<% } %>
<% } %>
This method allows flexibility to locally serve js files from any page and also prevent any reference errors caused by dependencies.
In pipeline.js insert '!js/local/*.js at the bottom of jsFilesToInject like so:
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
// Dependencies like jQuery, or Angular are brought in here
'js/dependencies/jquery-3.3.1.min.js',
'js/dependencies/**/*.js',
// All of the rest of your client-side js files
// will be injected here in no particular order.
'js/**/*.js',
//Ignore local injected scripts
'!js/local/*.js'
];
Create a local folder inside the /assets/js folder ie /assets/js/local/. Place any locally injected scripts in here.
In your master view ejs ie layout.ejs insert <%- blocks.localScripts %> below the SCRIPTS block like this:
<!--SCRIPTS-->
<script src="/js/dependencies/sails.io.js"></script>
<script src="/js/dependencies/jquery-3.3.1.min.js"></script>
<script src="/js/dependencies/bootstrap.min.js"></script>
<script src="/js/dependencies/popper.min.js"></script>
<!--SCRIPTS END-->
<%- blocks.localScripts %>
In your local ejs view (eg. homepage.ejs) insert your localScripts block like this:
<% block('localScripts', '<script src="/js/local/homepage.js"></script>') %>
sails v0.12.14
EDIT
Is this still relevant for Sails v1.0?
My answer is a resounding YES and in my earlier answer I lacked explaining how to get the most out of the Grunt pipeline like clean, coffee, concat, uglify etc... when going into production.
The trick here is to make a local file (there should only be one per page) as small as possible.
Group and name specific your function calls
Save functions as separate files for easy maintenance and group them into folders.
Group bindings and any initialising of global variables into a couple of functions like initThisPageVariables() and initThisPageBindings() so that Grunt can crunch these later.
Set a master function call to run your app startThisPageApp()
Then simply calling the few functions from your local (master) file to get things rolling.
$(window).on('load', function(){
initThisPageVariables();
initThisPageBindings();
$(window).on("resize", function(){
initThisPageVariables();
}).resize();
startThisPageApp();
});
I know this is an old question by I discovered another option.
File:
config\routes.js
Code:
'/': 'HomeController.StartHome'
I set StartHome function in HomeController responsible for managing '/' route.
File:
api\controllers\HomeController.js
Code:
StartHome: function(req, res) {
var template_data = {
"data" : {
"view_name" : "home_view"
}
}
res.view('home_view', template_data)
}
Here, I created an object with some data which is passed to EJS template(to client).
File:
views\layout.ejs
Code:
<% if (data["view_name"] === "home_view") { %>
<script src="script_for_home_view.js"></script>
<% } %>
In my layouts.ejs I created if statement which "enables" script tag depending on on the view I am currently on.
This is how I handle this. I hope it's clear for you.
Sails 0.12.4

Loading content into tooltip via ajax

I am using this Plugin to load content into tooltip via ajax. It is pretty simple to understand and start using it.
This is my jsp page in which I want to load content dynamically into tool tip on hovering on a link.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.hoverIntent.js" type="text/javascript"></script> <!-- optional -->
<script src="jquery.cluetip.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a.basic').cluetip();
});
function web()
{
alert('asffdsr');
}
</script>
</head>
<table border="1">
<tr>
<th>Question name</th>
<th>Group ID</th>
<th>opt1(#votes)</th>
<th>opt2(#votes)</th>
<th>opt3(#votes)</th>
<th>opt4(#votes)</th>
<tr>
<c:forEach var="questions" items="${questionslist}">
<tr>
<td><a class="basic" href="http://www.google.com" rel="http://www.google.com" ><c:out value="${questions.question}"/></a></td>
....
If you look into the above code, at the bottom you will find the <a> tag with class = basic and the page to be loaded into the tooltip via ajax is http://www.google.com
In the head you can see the script src and the javascript functions. I have imported the all the js files into the folder containing the jsp page.
But for some reason the tooltip is not appearing. What is wrong here and how to correct it? And also is there any way of checking if all the 3 js files jave been imported into the page?
The following structure describes where the css and the jsp files are present. The css and js fields are present inside the web content folder and the jsp files are present in
WEB CONTENT
WEB-INF
JSP FILES..
CLUETIP CSS AND JAVASCRIPTFILES..
This is the screenshot. As you can see the js fields are not being loaded. But the css files are being retrieved.
EDIT#1
The page is loaded via ajax inside a div. So on clicking view page source, we cannot see the the source code of the stuff inside the div.
EDIT#2
The jquery.js file is not being imported even when using CDN i.e in the network tab of the developer tool, there is no call made for the the javascript file. I have given the script src line in the head section.
EDIT: Based on the edits to the question here is what is going on. When you load content on a page via Ajax, any script tags in that content will not be executed. See this question: Loading script tags via AJAX for more details. Be sure to read all the answers, as the solution may be dependent on your particular scenario.
Original Answer
You're trying to do an ajax request from your site to another domain, google.com. This is not allowed by browsers, its called a cross domain request. According the the qtip error handler:
error: function(xhr, textStatus) {
if ( options.ajaxCache && !caches[cacheKey] ) {
caches[cacheKey] = {status: 'error', textStatus: textStatus, xhr: xhr};
}
if (isActive) {
if (optionError) {
optionError.call(link, xhr, textStatus, $cluetip, $cluetipInner);
} else {
$cluetipInner.html('<i>sorry, the contents could not be loaded</i>');
}
}
}
you should be getting the following: <i>sorry, the contents could not be loaded</i> loaded into your tooltip (see jsfiddle). Check the error console, the most obvious answer is that you are getting a 404 error on one of your files, which should show up in the developer tools of whatever application you are using. See what happens in this fiddle where I replace 'cluetip' with a non existant javascript file. The chrome developer console looks like this:

ASP.NET WebForms Routing Javascript Error

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.

Categories

Resources