javascript path with Url.Content - javascript

I am trying to get standard path with javascript for images in my project
I used src for image as below
document.testImg.src = '../Images/test.png';
Do we have any option like below to make path consistent?
document.testImg.src = '#Url.Content(~/Images/test.png)';
<img name="testImg">
Thanks in advance

As you probably know you can't use Razor in Javascript unless that script is part of the Razor view. It's not the "sexiest" way but one way out is to have a "global" javascript URL variable in your Layout View/MasterPage.
for example in your shared layout you'll have a variable:
var AppUrl = '../Content/Images/';
so then in all your views you can use this consistent variable:
var myImageUrl = AppUrl + 'image.jpg';
p.s. Don't want to use variables ? Stick a function in your shared view instead:
For example in your shared layout you'll have a function:
function AppURL(url)
{
return '../Content/Images/' + url;
}
so then in all your views you can use this:
var myImageUrl = AppUrl('image.jpg');

I found a good solution for this. I used t4mvc for my project and updated all my magic strings. I thought this solution would be useful for few developers who have issues with paths.

This way we can use Url.Content() few example code i added that may help others.
<p>This link goes to my ``Application home page.</p>
<p>Now let’s link to a view ``in the Controller/Action directory.
Url.Content("~/img/myImage.png")
<img src= "#Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>

Related

Image autoslider for dynamic folder's content

I'd like to make autoslide gallery.I wonder how to start it... It got to be dynamic, because folder content will change with time. Typing is not what I'm looking for. Can You give me any advices or tutorials I can base on? I was searching but there's no for dynamic folder content...
This is a very generic example and may not be direct copy/paste for you but it should help you learn the fundamentals of achieving your intended result.
Using this library:
https://gist.github.com/tsohil/623538
Assuming you want to get all of the images in the folder.
First, we'll use PHP to fetch the file names doing so along the lines of:
<?php
echo json_encode(glob("folder/relative/to/controller/*.{jpg,png,gif}", GLOB_BRACE));
Our HTML we will stage as:
<div id="carousel"></div>
Then in our JS (example requires jQuery) we will send a request for to that.
$.get('/phpcontroller.php', {}, function(data) {
data.forEach(function(val) => {
$("#carousel").append("<div class=\"inactive\">
<img width=\"946\" height=\"473\" src=\"/path/to/folder/"+val+"\" class=\"car-img\">
</div>");
});
});

How do I set an image url from Javascript

I am writing an Open University project that requires me to use Cordova to generate an Android app. To do this, I am using a combination of HTML and JavaScript.
My HTML uses
<div data-role="page" id="view">
etc. to define individual pages within the single HTML file. When the page first runs, it shows a "corporate" logo. After signing in, it shows the personal logo. The url to the logo comes from a database and is held in a JS global variable railroadLogoPath. I have an HTML placeholder Once I move to another page, I can't see how to get the HTML to use the JS to get the url of this logo.
My HTML looks like this:
<img class="banner" id = "signedInlogo" width = "100%">
I have a JS function in index.js as follows:
function insertLogo(anID) {
document.getElementById("anID").src = railroadLogoPath;
}
How do I call this from HTML. I have tried putting it in
<script> insertLogo("signedInLogo")</script>
but this doesn't work.
I am just starting to understand JS so any help would be appreciated.
David
In this line:
document.getElementById("anID").src = railroadLogoPath;
You're looking for an element by ID with the literal string "anID". You should be using the variable anID
function insertLogo(anID) {
document.getElementById(anID).src = railroadLogoPath;
}

How to document.write() within an image src string? Doesn't get parsed

This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle

changing img src with JQuery but leave pathing info intact?

I'm using JQuery to switch out an image src thusly:
$("#myImg").attr("src", "../../new.gif");
notice the relative pathing on the new src. Unfortunately, this isn't portable when I deploy my app. In my MVC app I'm using a ResolveUrl() method that will fix the pathing problem for me so it's portable, but now my JQuery image src swapper doesn't work right since it now switches the correctly resolved path to a broken relative one.
<img id="myImg" src="<%=ResolveUrl("~/Images/transparent.gif")%>" />
What I want is for JQuery to just flip the actual filename and leave the path untouched. My first thought would be to
// pseudocode javascript jquery on my thought on how to approach this prob
var oldFullPath = $('#myImg").GetTheImgSrc;
var newFileNameWithPathIntact = someRegexAddNewFileNameWithOldPath
$("#myImg").attr("src", newFileNameWithPathIntact);
but that seems rather gross and un-JQuery to me. Anyone got a better way?
you could use something like this:
var oldImage =$("#myImg").attr("src");
var imagePath = oldImage.slice(0, oldImage.lastIndexOf("/")) + "/new.gif";
$("#myImg").attr("src", imagePath );
EDIT: better code...:)
You can use the resolveurl right in the javascript:
$("#myImg").attr("src", "<%=ResolveUrl("~/Images/new.gif")%>");
That of course assumes that you've included the javascript right in the view. If you have a requirement that this script must live in a separate script file from the html request, then you can just have a view which is a javascript file ... and just reference that URL in the script src:
<script language="javascript" src="<%= Url.Action("MyMethod") %>" />
why not just use a variable for the root of the app that you can use for these types of situations.
var root = "<%=ResolveUrl("~/") %>";
Now you can easily construct your image path
$("#myImg").attr("src", root + "images/" + fileName);

How to handle localization in JavaScript files?

I want JavaScript code to be separated from views.
I got the requirement to implement localization for a simple image button generated by JavaScript:
<img src="..." onclick="..." title="Close" />
What's the best technique to localize the title of it?
PS: I found a solution by Ayende. This is the right direction.
Edit:
I got Localization helper class which provides the Controller.Resource('foo') extension method.
I am thinking about to extend it (helper) so it could return all JavaScript resources (from "ClientSideResources" subfolder in App_LocalResources) for the specified controller by its name. Then - call it in BaseController, add it to ViewData and render it in Layout.
Would that be a good idea?
EDIT
Consider writing the necessary localized resources to a JavaScript object (hash) and then using it for lookup for your dynamically created objects. I think this is better than going back to the server for translations. This is similar to adding it via viewdata, but may be a little more flexible. FWIW, I could consider the localization resources to be part of the View, not part of the controller.
In the View:
<script type="text/javascript"
src='<%= Url.Content( "~/Resources/Load?translate=Close,Open" %>'></script>
which would output something like:
var local = {};
local.Close = "Close";
local.Open = "Open";
Without arguments it would output the entire translation hash. Using arguments gives you the ability to customize it per view.
You would then use it in your JavaScript files like:
$(function(){
$('#button').click( function() {
$("<img src=... title='" + local.Close + "' />")
.appendTo("#someDiv")
.click( function() { ... } );
});
});
Actually, I'm not too fussed about keeping my JavaScript code out of my views as long as the JavaScript code is localized in a container. Typically I'll set my master page up with 4 content area: title, header, main, and scripts. Title, header, and main go where you would expect and the scripts area goes at the bottom of the body.
I put all my JavaScript includes, including any for viewusercontrols, into the scripts container. View-specific JavaScript code comes after the includes. I refactor shared code back to scripts as needed. I've thought about using a controller method to collate script includes, that is, include multiple scripts using a single request, but haven't gotten around to that, yet.
This has the advantage of keeping the JavaScript code separate for readability, but also allows me to easily inject model or view data into the JavaScript code as needed.
Actually ASP.NET Ajax has a built-in localization mechanism: Understanding ASP.NET AJAX Localization
If you insist on keeping it separate, you could do something like:
//keep all of your localised vars somewhere
var title = '{title_from_server}';
document.getElementById('someImage').title = title;
Remember, if you use JavaScript code to initialize any text of elements, your site will degrade horribly where JavaScript isn't available.

Categories

Resources