Javascript Link to Subdomains - javascript

I am developing an ASP.NET MVC website.
The dev website is on the root , so I can access it directly at http://localhost.
In the production machine, it is not on the root, so it should be accessed by: http://server/mywebsite.
In the view, I have a link to edit the object by calling an action method on the controller so that I can call it by: /School/Edit/1
however on the production, this will not work, I need to call it as: /mywebsite/School/Edit/1
In order to solve this, I did the following in the Javascript file:
var APP_PATH = "/mywebsite/";
function getEditLink(controller,action, id) {
return "<a href='" + APP_PATH + controller+"/"+ action + "/" + id + "'>" +"Edit"+"</a>";
}
on the development, I set the APP_PATH to an empty string, when I need to upload to the production I set it to "/mywebsite/".
I know there should be some mapping to do this instead of doing it like what I did, something like the Server.MapPath("~") in ASP.Net.

Related

MVC4 and dropdown using onchange

I've searched several posts on this and the methods all would normally work, however...
I'm in an environment where we use 3 different servers (Dev, UAT and Prod). All 3 have differing URL structures:
http://dev.com/myusername/applicationname (Dev)
http://uat.com/applicationname (UAT)
http://prod.com/applicationname (Prod)
The issue that I'm having is when I try to use a dropdown I'm having problems getting the url right. The issue is when I use the following code to populate my dropdown:
#Html.DropDownList("Owners", ViewData["Owners"] as SelectList, new { onchange = "document.location.href='/Builds/' + this.options[this.selectedIndex].value;" })
It handles the event just fine, but produces a URL of:
http://dev.com/Builds/value. I need it to be http://dev.com/myusername/application/Builds/value.
Any ideas on how I can accomplish this?
Get the base uri then append your stuff to that:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
Note that the trim is there because it may or may not end with the trailing slash depending on where it is hosted (root or sub directory)
You might also be able to use
HttpContext.Current.Server.MapPath("~/Builds/")
This might also work:
#HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)#Url.Content("~/Builds/")

403 Error using JavaScript to access folder

In a .Net Web Forms project am trying to use JavaScript to display all images in a folder. Using the following script gives me a 403 error
<script>
var dir = "fullimages/";
var filext = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + filext + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http:///", "");
$("body").append($("<img src=" + dir + filename + "></img>"));
});
}
});
</script>
But I am not quite sure why? I have checked around the site and found the following suggestion 403 forbidden error while getting javascripts under root folder. In my case JS is not on the list of handlers.
If I have got this right your trying to run Javascript on the server side. Are you using any particular framework, node JS for example?
Secondly what server architecture are you running, windows (IIS) / linux (APACHE, N GINX) etc...?
From having a brief read of your linked question, have you tried moving this script into the fullimages directory and then request that?

Run script in wkhtmltopdf process

I use wkhtmltopdf to create pdf(s) from html(s)
I have next function :
private void CreateTempPdf(string htmlPath, string pdfPathTemp)
{
var processorInfo = new System.Diagnostics.ProcessStartInfo
{
Arguments =
"--margin-top 27 \"" + htmlPath + "\" \"" + pdfPathTemp +
"\" ",
FileName = PublisherConfigurationManager.Pdf2HtmlConverter,
UseShellExecute = true
};
using (var proc = new System.Diagnostics.Process())
{
proc.StartInfo = processorInfo;
proc.Start();
proc.WaitForExit();
}
}
in which i pass paths of html file and destination file.
I want to add some js script to run, before pdf will be generated.
I add my code : --run-script <js> into Arguments after pdfPathTemp but script isn't applied to pdf. I also add it before --margin but this case also doesn't help me.
How correctly add scripts into wkhtmltopdf process?
I would simply add the script directly into the HTML page. In this case I would load the HTML from the path into a string, inject the script, then write a tempfile for the process duration.
As for why --run-script does not work, I have no idea. Have you tried it directly in the command line with a very simple script and HTML to see if a minimal example works for you?
If that is not an option, you might have to play around with different files for differnt js arguments, if you require such things.

Configuration files for javascript so base url can be changed

We are using AJAX to call WCF services from various sub folders.
So the urls of the DOM OBJECT window.location.HREF
would be :
http://localhost:80/myVirtualDirectory/Reporting/reporting.aspx
OR
http://localhost:80/myVirtualDirectory/Sales/sales.aspx
My service actually resides at:
http://localhost:80/myVirtualDirectory/
When I am calling from a "sub folder" the service cannot be found or I have to put *.svc files in parent and all sub folders.
So need all my AJAX "url" to start with
http://localhost:80/myVirtualDirectory/
Only I don't know what myVirtualDirectory is going to be as we deploy this application to our customers' web sites.
I wrote a scriptblock to push this out as:
var urlBase = "http://localhost:80/myVirtualDirectory/"
The code in C# was like this (abridged)
"var urlBase = '//'+window.location.host+" + Request.ApplicationName + " '/' ";
Is there a better way?
Please keep in mind that we are moving away from ASPX in favour of plain old html pages(POHP) with knockout.js
You could try using the <base> tag on your HTML:
<head>
<base href="http://localhost:80/myVirtualDirectory/">
</head>
You might be able to use servletContext.getContextPath():
http://docs.oracle.com/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/javax/servlet/ServletContext.html#getContextPath()

How should I create relative paths in javascript using MVC3?

I am having some difficulty aligning my paths without a hardcode in javascript. I am running an asp.net MVC3 web application.
If my path is of the form
var url = 'http://serverNameHardcode/websiteNameHardcode/service/service?param1=' + param;
Then things work fine when I do
$.get(url,
{},
function (data) {alert('callback success');},'json');
I would like to create a relative path. I tried
var url = 'service/service?param1=' + param;
And this works when I run locally and also in Firefox, but not in IE7. When I publish to the server without the hardcode the callback never fires. I know MVC-3 adds some complexity to routing, but I do not know if it applies to this situation; so, I marked this question as such.
How should I setup my path so I don't need hardcodes?
Just write out the app path as a global js variable from your master view, then compose links as
APPPATH + "path/whatever"
Just had to solve this for one of my jQuery plugins, where it is preferable not to modify anything global (i.e. outside the scope of the plugin use) so I had to disregard the marked answer.
I also found that because I host DEV locally in IIS I could not use a root-relative path (as localhost is not the root).
The solution I came up with extended what I had already started with: a data-controller attribute specifying which controller to use in the element I am applying my plugin to. I find it preferable to data-drive the controller names so the components can be more easily reused.
Previous:
<div data-controller="Section">
Solution:
<div data-controller="#Url.Content("~/Section")">
This injects the server root (e.g. /Test.WindowsAzure.Apr2014/ before the controller name so I wind up with /Test.WindowsAzure.Apr2014/Section which is perfect for then appending actions and other parameters as you have. It also avoids having an absolute path in the output (which takes up extra bytes for no good reason).
In your case use something like:
// Assuming $element points to the element your plugin/code is attached to...
var baseUrl = $element.data('controller');
var url = baseUrl + '/service?param1=' + param;
Update:
Another approach we now use, when we do not mind injecting a global value, is Razor-inject a single global JavaScript variable onto window in the layout file with:
<script>
window.SiteRoot = "#Url.Content("~/")";
</script>
and use it with
var url = window.SiteRoot + '/service?param1=' + param;
One option:
var editLink = '#Url.Action("_EditActivity", "Home")';
$('#activities').load(editLink + "?activityID=" + id);
another example:
var actionURL = '#Url.Action("_DeleteActivity", "Home")';
$('#activities').load(actionURL + "?goalID=" + gID + "&activityID=" + aID);
If you don't need to add to the string:
$('#activities').load('#Url.Action("_Activities", "Home", new { goalID = Model.goalID},null)');
I really need the path to get this to work, maybe its IE7. Who knows. But this worked for me.
Grab the URL and store it somewhere. I chose to implement the data attribute from HTML5.
<div id="websitePath" data-websitePath='#Request.Url.GetLeftPart(System.UriPartial.Authority)#Request.ApplicationPath'></div>
Then when you need to perform some AJAX or otherwise use a URL in javascript you simply refer to the stored value. Also, there are differences in the versions of IIS (not cool if your devbox is IIS5 and your server is IIS7). #Request.ApplicationPath may or may not come back with a '/' appended to the end. So, as a workaround I also trim the last character if it is /. Then include / as part of the url.
var urlprefix = $('#websitePath').data('websitepath');
urlprefix = urlprefix.replace(/\/$/, "");
var url = urlprefix + '/service/service?param1=' + param;
While the accepted answer is correct I would like to add a suggestion (i.e. how I do it).
I am using MVC, and any ajax request goes to a controller. My controllers have services so if a service call is required the controller will take of that.
So what's my point? So if ajax always communicates with a controller, then i would like to let the MVC routing resolve the path for me. So what I write in Javascript for url is something like this:
url: 'controller/action'
This way there is no need for the root path etc...
Also, you can put this in a separate Javascript file and it will also work whereas #Url.Content will need to be called on the view.

Categories

Resources