How to set relative path to script from ascx - c#

I have created custom DNN module.
And I want to use masonry plugin in it.
So in the module project in VS I have created Scripts folder and put JS files in there.
On the view of ascx file I have added:
<script src="Scripts/jquery.infinitescroll.min.js"></script>
<script src="Scripts/masonry.pkgd.js"></script>
<script src="Scripts/imagesloaded.js"></script>
But when I load the page eith module in console I get:
GET http://dnn7site/resources/shared/scripts/jquery/jquery.min.map 404 (Not Found) Masonry:457
GET http://dnn7site/jquery.min.map 404 (Not Found) Masonry:464
GET http://dnn7site/Demos/Scripts/masonry.pkgd.js 404 (Not Found) Masonry:751
GET http://dnn7site/Demos/Scripts/imagesloaded.js 404 (Not Found) Masonry:752
GET http://dnn7site/Demos/Scripts/jquery.infinitescroll.min.js 404 (Not Found)
What is the way to add and set a relative path to the scripts in DNN?

You should be using the client dependency framework to include scripts in DotNetNuke (feature was added in DNN 6.1+). It will control priority and allow the framework to combine scripts together for a more efficient payload.
The wiki entry for the information is here:
http://www.dnnsoftware.com/wiki/Page/Client-Resource-Management-API
In essence, it's as easy as this:
<%# Register TagPrefix="dnn" Namespace="DotNetNuke.Web.Client.ClientResourceManagement" Assembly="DotNetNuke.Web.Client" %>
<dnn:DnnJsInclude runat="server" FilePath="~/Resources/Shared/Scripts/jquery/jquery.hoverIntent.min.js" />
If you want to do it through code, try this:
RegisterStyleSheet(Page page, string filePath) //default provider and default priority

For scripts or css in my custom module, I usually put the call to ClientResourceManager in my control's PreRender event. I use the ControlPath to get the relative path of my module control to reference the scripts. Example:
protected override void OnPreRender(EventArgs e)
{
ClientResourceManager.RegisterStyleSheet(this.Page, this.ControlPath + "css/view.css");
ClientResourceManager.RegisterScript(this.Page, this.ControlPath + "js/view.js");
}

Try including the full path to the resource files, as per the instructions on the Masonry getting started documentation:
Include the Masonry script in your site.
<script src="/path/to/masonry.pkgd.min.js"></script>
For example:
<script src="/desktopmodules/com.demo.masonry/Scripts/jquery.infinitescroll.min.js"></script>
<script src="/desktopmodules/com.demo.masonry/Scripts/masonry.pkgd.js"></script>
<script src="/desktopmodules/com.demo.masonry/Scripts/imagesloaded.js"></script>

Related

Change CSS href link Dynamiclly

<link href="CSS/make.css" rel="stylesheet" />
This an external css file for a page named "Default.aspx" which is located in "Root/Pages" directory.
so In "Root/Pages" we will have these:
Default.aspx
CSS/make.css
It will work fine if I launch Default.aspx from current location, But user can change the directory of Default.aspx from main page. Then in Code-Behind I will copy all of Pages contents into another directory.
Just think I will copy Default.aspx and CSS folder from Root/Pages to Root/Backup and try to launch Default.aspx from new location. In this situation it can not read and load external css file!
How can I change css href link dynamically from its container page's location?
For example changing href="CSS/make.css" to href="BackUp/CSS/make.css".
After some research I found that I should use Global and URL Routing, but I did not get any working result.
If you put the css file in the root directory then refer to it using:
<link href="/make.css" rel="stylesheet" />
It should now work even when you move your Default.aspx to another location. The downside to this is that it can clutter your root directory if you plan to use it for multiple different pages with different CSS files.
Let me know if it works and if I am understanding your question right.
function DynamicURL()
{
var URL='CSS/make.css';
var BackUp ='BackUp/';
if (Your condition when it changes directory)
URL = Backup + URL;
document.getElementById('Field').href= URL;
}
Don't forget to set ID to your link href field.

0x800a1391 - JavaScript runtime error: 'jQuery' is undefined

I have a ASP .Net MVC4 Web application. In it I have my usual html for the _Layout.cshtml, which in turn loads the default Home/Index. All works fine.
In my index I am also loading a partial view. This works fine too. No probs.
I am using a the UI tools from the following site:
http://www.keenthemes.com/preview/index.php?theme=metronic
The problem is it seems to be primarily HTML4 and not designed for MVC out of the box so I am having to tweak it slightly to get it to work the way I want. (Nothing beyond anything very basic). For example, moving one part out to the index and using Renderbody() to load it so the actual html structure never changes. I have done this a million times to be sure I am not missing any closing tags or anything else that could cause my problem.
Up to this point there is no problem at all. Everything loads as it should.
I continued to create a 2nd View and its partial to extract other parts of the site. As usual, baby steps first. Before extracting any other code, I just used a little "Hello World" in the first page, and a similar string in the partial to be sure it was working. It was.
Now when I type in the url Home/ActionName the whole thing reloads as it should but looks horrible. and I get this error message:
0x800a1391 - JavaScript runtime error: 'jQuery' is undefined
Below is my code which clearly defines it:
<!-- BEGIN CORE PLUGINS -->
<script src="assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function ()
{
App.init(); // initlayout and core plugins
_Layout.init();
_Layout.initJQVMAP(); // init index page's custom scripts
_Layout.initCalendar(); // init index page's custom scripts
_Layout.initCharts(); // init index page's custom scripts
_Layout.initChat();
_Layout.initDashboardDaterange(); //Red date range
_Layout.initIntro(); //Pop up messages
});
</script>
It points me to the jQuery(document).ready part when I see the message.
Again, when I load the page normally, it works fine. When I type Home on its own it works fine. Its only when I type Home/AnythingElse that it gives this error message. Even if I type Home/ which should load in the Index file, it gives me this error message.
jQuery is defined, so why is this happening on postback?
Any help is appreciated.
Try setting the src for jQuery to be absolute from the site root:
<script src="/assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
Note the / before assets - when your src path does not start with a / the browser will try and load the asset relative to the current path, so in your example when you add the trailing slash to Home it will try to load jQuery from Home/assets/plugins/...
For me, the MVC bundlers were causing problems (in my case the ui bundler)
Here is the order which worked for me.
<script src="/Scripts/modernizr-2.5.3.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/bundles/jquery-ui"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
You need to add the jquery-x.xx.x.js first before the validate.js like this
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>

Embedding javascript tag in child page

I have a JavaScript code which links to survey poll page. When I am embedding the JavaScript code in normal aspx page (without master page), I am getting the survey normally without any issues, but when I am embedding the same code in page which uses master page, I am getting blank page.
This way doesn't work: http://gyazo.com/27f38b5b04897cf0b17747eab05cf746
This way works: http://gyazo.com/c69d3b95afe4a0070cd09834e479a97f
Update
Using <script src='<%=ResolveClientUrl("~/Survey/xlaabsolute.asp?p=1")%>' type="text/javascript" /> renders the poll correctly but the button for voting doesn't do any postback http://gyazo.com/b39fcaa8de3438c8c2a625e3816ba4be.
I can see the content http://gyazo.com/b39fcaa8de3438c8c2a625e3816ba4be
Chances are it's how the script is referenced.
You're using a relative position in your src attribute which could potentially change if it's not in a location that allows Survery/... to be found. Maybe change it to /Survey/... so it always locates the file based on the root path and not where the document currently resides?
You can also make your script tag runat="Server" and reference the script using traditional ASP relative links: src="~/Survey/..." so it resolves correctly.
The way to resolve the issue and make it work regardless of where the control is being used is to use ResolveClientUrl as so:
<script src='<%=ResolveClientUrl("~/Survey/your_script.js")%>' type="text/javascript" />

inline Server Code for C# Fails to work when moved to a JavaScript .js file

Within my C# code behind page, I have the following:
MembershipUser currentUser = Membership.GetUser(false);
HttpContext.Current.Session["UserGuidAsString"] = currentUser.ProviderUserKey.ToString();
At the bottom of the corresponding ASPX page, I have the following code:
</form>
<script type="text/javascript"> var userGuidAsString = '<%=Session["UserGuidAsString"]%>';
alert(userGuidAsString);
</script>
</body>
</html>
It gives the proper expected result which is an alert box with the User's GUID when I run the page
I wanted to move the JavaScript code to a .js file so that the code is more modularized and organized.
I created the following test.js javascript file with the following contents:
var userGuidAsString = '<%=Session["UserGuidAsString"]%>';
alert(userGuidAsString);
I also modified the ASPX page so that it would include the test.js javascript file:
</form>
<script src="/Scripts/test.js" type="text/javascript"></script>
</script>
</body>
</html>
It fails because it just gives an alert box with
'<%=Session["UserGuidAsString"]%>'
as a message
May I please know how I can make in line server C# code work within JavaScript .js files?
By This your accessing Server Variable
'<%=Session["UserGuidAsString"]%>'
its not functionlity of Javascript.
You can write this code without js block also..
its like ASP code..
so its workg with .aspx page only not in javascript
A common workaround for this is to put the server variable in an html hidden element. For example:
<input type="hidden" id='guid' value='<%=Session["UserGuidAsString"]%>' />
Then your javascript file:
var guid = document.getElementById("guid").value;
Or, you could define a js variable in your html, and reference that in your js file. Just make sure to declare the variable before you reference it.
<script type="text/javascript">
var guid = '<%=Session["UserGuidAsString"]%>';
</script>
<script type="text/javascript" src="yourScript.js></script>
Then in your js file you can simply use the guid variable.
In order for C# to get executed on the server before the .js file reaches the client, you'd have to register that page extension in IIS so that the asp_net .dll processes .js files.
In your particular case (handling GUIDs), you really don't want to go this route, because with the nature of .js file caching, you're going to have a lot of problems ensuring that it's a fresh version being served up every time.
I suggest recreating a very simple (and yes, modular/reusable) JS function that makes a call to, say, GetUserGuidAsString.aspx by using AJAX or the equivalent.

HTML helpers in ASP.NET MVC 3 with Javascsript action

I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}
With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.
You can put a <script> tag in the helper body.
How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}

Categories

Resources