Pass variable to JS file - c#

Although this question have been asked and answered before, including on this website, I am not managing to solve my problem.
I am using Masterpages, and Javascript files... and everyone now how "tricky" masterpages get with relative paths...
Well, I am using a png fix called: unit Png Fix (quite good to be honest... even better than the JQuery one), and this fix needs to use a small image called clear.gif.
The path to the clear.gif file is being stored inside a variable that is in the JavaScript file.
However, and since I am using Masterpages I cannot simply open the JS File and write a static path... has i thought.
What I tried was: remove the variable from the JS File, and declare it outside, but in the sabe Script block. Like this:
<!--[if lt IE 7]>
<script src="<%= ResolveClientUrl("~/masterpages/js/unitpngfix.js") %>" type="text/javascript">
var clear="<%= ResolveClientUrl("~/masterpages/img/clear.gif") %>";
</script>
<![endif]-->
I even tried to declare it in the Head of the website. (I'm placing my JS files at the bottom of my page, to speed it up).
Unfortunately my solutions didn't work... which is why i am doing this question here. :(

You can't declare a src and content in a single element.
from the script element definition on the W3C site:
If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI
Try separating them:
<script type="text/javascript">
var clear="<%= ResolveClientUrl("~/masterpages/img/clear.gif") %>";
</script>
<script src="<%= ResolveClientUrl("~/masterpages/js/unitpngfix.js") %>" type="text/javascript"></script>

A) you can declare both the src attribute for a Javascript resource and information within the block. You'd need to do declare the clear in it's own block prior to the src block
B) The way I've accomplish passing code-generated URLs to Javascript is in my view/masterpage I have a script block that declares a url array attached to the Window so that way there isn't odd conflicts down the road with other scripts:
<script type="text/javascript">
Window.url = {
clearImage: '<%= ResolveClientUrl("~/masterpages/img/clear.gif") %>',
otherUrl: '<%=ResolveClientUrl("~/other/file/...")%>'
};
</script>
then in your actual script files you can get it via
var img = window.url.clearImage;
It does bind the script to that specific view, but I don't see that as a horrible thing.

Related

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>

HTML Helper in JavaScript?

In Razor I can do this:
<p #Html.MyCustomDataAttributeFor(person) >#person.Name</p>
To render something like this:
<p data-custom-person-id="1234567890" >Fred</p>
Must I really then do this in (unobtrusive) JavaScript:
$('p[data-custom-person-id="1234567890"]').css('background-color','red');
When I'd prefer to do this:
$('p[#Html.MyCustomDataAttributeFor(person)]').css('background-color','red');
If only I could, otherwise should the data attribute generated by the HTML helper change, my client side code will no longer style the element.
Could you point the script to a .cshtml-file?
<script type="text/javascript" src="/myscript.cshtml"></script>
I think I've done this for both .php and .aspx so I don't see a reason it shouldn't work.
In those cases it makes the server first process the file.
Otherwise you could use a customer HttpHandler that parses whatever text you want server-side before it's sent to the client.
The easiest however, would be to set some Javascript variables from Razor, ie:
<script type="text/javascript">
var customerId = '#Html.MyCustomDataAttributeFor(person)';
</script>
And then write:
$('p[' + customerId + ']').css('background-color','red');
data-custom-person-id="1234567890" is rendered to the browser after server has converted #Html.MyCustomDataAttributeFor(person) to that value. On the client side you will not be receiving these text at all. So, you cannot use those statements for client side styling.

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.

how to render the relative path with tilde into ../../ of relative path in jquery/javascript?

Well, i understand my title is a bit confusing. I will state it clearly below with the example.
<asp:ImageButton ID="imgButton" NavigateUrl="~/Presentation/Resources/Images/addFile.png" runat="server" />
In html, the control above will be rendered as
<input type="image" name="imgButton" id="imgButton" src="../../Resources/Images/addFile.png" style="border-width:0px;">
I notice that,it will convert the src from "~" to "../../" .It auto arrange it will the file level.
so in javascript, i want to set it the control with this url :
~/Presentation/Resources/Images/PDF.png
unfortunately, in html it will be rendered as
<input type="image" name="imgButton" id="imgButton" src="~/Presentation/Resources/Images/addFile.png" style="border-width:0px;">
My question is, What should i write if i wanna get the "../../" relative path with "~" ?
I have tried this,but i cant get it.
<script type="javascript">
document.getElementById("<%= imgButton.ClientID %>").src =
"~/Presentation/Resources/Images/PDF.png";
</script>
Try this: http://weblogs.asp.net/joelvarty/archive/2009/07/17/resolveurl-in-javascript.aspx
In the master page for the site, put this:
<script type="text/javascript">
var baseUrl = "<%= ResolveUrl("~/") %>";
</script>
Then, in your javascript file, put this function:
function ResolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url;
}
You could have put the function right in the master page, but then you
wouldn’t get intelli-sense on it for the rest of your code. Now you
can call ResolveUrl with ~/ right from javascript.
Why do you need this on clientside? Use servercontrols(runat=server) and you can use tilde to resolve URL on server.
Actually, URLs with tilde get converted to absolute URL thanks to the methods :
ResolveURL and ResolveClientURL
Therefore you should be able to do this :
<input type="image" name="imgButton" id="imgButton" src="<%=this.ResolveClientUrl("~/Resources/Images/addFile.png")%>" style="border-width:0px;">
(this is actually done automatically for you in Web Controls like HyperLink and such)
The big difference with those two methods happens when you use User-controls. In a case, the URL refers to the URL relative to the folder where the user-control is, in the other case, that would be the page containing the user-control.
See also this question : Control.ResolveUrl versus Control.ResolveClientUrl versus VirtualPathUtility.ToAbsolute
Have a look at the VirtualPathUtility Class and this information from msdn about ASP.NET project paths.
The VirtualPathUtility.ToAppRelative method is probably what you're looking for.
VirtualPathUtility.ToAppRelative
If the virtual path for the application is "myapp" and the virtual
path "/myApp/sub/default.asp" is passed into the ToAppRelative method,
the resulting application-relative path is "~/sub/default.aspx".
It explains and gives examples on how to convert between different path formats.
I also think you should to output the correct path at server level instead of reverse engineering in javascript in the browser. It may cause issues if you rearrange your project and asp changes it.
WebControls translate the tilde into the correct path when run on the server before rendering the html, you will need to use the full path or relative path in jQuery if you're changing the src on the fly.
You might want to have a property on the page with the root path eg: ApplicationRootURL and do something like this:
<script type="javascript">
document.getElementById("<%= imgButton.ClientID %>").src =
"<%=ApplicationRootURL%>/Presentation/Resources/Images/PDF.png";
</script>

Categories

Resources