Url Helper ASP.NET MVC in Javascript - javascript

I'm writing a js script that read a file JSON that contains all navigation menĂ¹ links of my web application.
the menu tree is something like this:
1 - DASHBOARD - dashboard
2 - SETTINGS
2.1 - GENERAL - settings/general
2.2 - LAYOUT - settings/layout
3 - DATABASE
3.1 - QUERY
3.1.2 - EDITOR - database/query/editor
3.1.3 - TEST - database/query/test
the menĂ¹ is 3 levels nested link.
How can I write links in JSON file to avoid "not found" when e.g. in "DASHBOARD" and want to go to SETTINGS > GENERAL.
I don't want to use absolute path, my webapp will run in a virtual directory.

If you can, I wolud suggest modifying your JSON response to include the base path your app is hosted on.
string basePath = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
For example: basePath + "database/query/editor" instead of database/query/editor.
If you cannot modify the JSON response, you can get the base path your application is hosted on in a JavaScript variable from your MVC.
In your _Layout.cshtml file -- or whatever file that gets loaded every time your application is loaded -- set your base path that your application is running under in a JS variable:
<script type="text/javascript">
window.applicationBaseUrl = #Html.Raw(HttpUtility.JavaScriptStringEncode(Url.Content("~/"), true));
</script>
Now when you receive the JSON containing the URLs, concatenate them with your base path:
var queryEditorUrl = window.applicationBaseUrl + <the path from your JSON>
This way your URLs are independent of the virtual directory it is hosted on.

You should use Url.Content("~/") (see documentation) to get the absolute URL of your application. For example if you run your application in a virtual directory called MyApp and you have a page in About/Me you can use:
string url = Url.Content("~/About/Me"); // this will return '/MyApp/About/Me'

Related

How to set url in index.html in swagger-UI

I am using Swagger-UI for jax-rs jersey.
So there is this index.html. There you have to enter the url for the swagger.json .
So this is a big problem.
We are deploying our application to a lot different environments.
And the respective swagger.json will always be on the same environment.
We have Jenkins build jobs and we cannot edit index.html for every environment.
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "**https://petstore.swagger.io/v2/swagger.json**",
Property url I always have to set.
What should I do?
P.S.
In Springfox Swagger-UI there is no physical swagger.json
But in jax-rs I have this dist folder and there is always a physical json
as far as I understand. Where should I put this so all different
clients can access it.
You can use vanilla JS for that:
var currentUrl = window.location.origin;
var apiBasePath = currentUrl + '/v2';
window.ui = SwaggerUIBundle({
url: apiBasePath + "/swagger.json",
...
})

Get to know domain and context root url path in AngularJS

My angularJS application is running in a web server with the following path
http://www.some.domain.com/some/path/
Notice that /some/path/ is dynamic path because my app can be deployed to any web server to any directory. I need to get this absolute URL in AngularJS excluding all inner angular pages. For instance, if current user's page is
http://www.some.domain.com/some/path/inner/angular/page.html
then the code that I am looking for should return
http://www.some.domain.com/some/path/
You cannot use $location because it only has information about the current SPA.
The code that you are looking for ("/some/path/") is this:
var myContextWithPath = $window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/"));
Other variation that returns only the context ("/some") is this:
var myContext = $window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
You can also obtain the origin ("http://www.some.domain.com"):
var origin = $window.location.origin;
You can use $location for this. Don't forget the add $location in to controller function
$location.host()
gives you base url.Which is application base server domain, like : www.example.com
$location.port()
gives you port like : 8080
$location.path()
gives you where you are : index.html

How to handle links in Phonegap + JQM app?

I am building an app with Phonegap and jQuerymobile. The app roughly works like this:
1) The app downloads a ZIP file from a public server and then unzips them to a local folder. I got the local folder path from fileSystem.root.toNativeURL() (in OS, it's something like this: file://var/mobile/Container/Data/Application/xxxx/Documents/)
2) App redirects to HTML that was unzipped in local folder (ex: file://var/mobile/Container/Data/Application/xxxx/Documents/index.html)
I am now facing issues b/c inside the index.html file, all the links are absolute path (ex: Link). This breaks all the links since (I assume) they are all now pointing to file://content/index2.html instead of file://var/mobile/Container/Data/Application/xxxx/Documents/content/index2.html.
My question is, how should I handle the links? I am thinking i should just rewrite all the links to force prepend the local folder URL in front of it. Is there a better way?
And if rewriting links is the way to go, how can I do this with jQuerymobile? I did this in jQuery which seems to work http://jsfiddle.net/jg4ouqc5/ but this code doesn't work in my app (jQueryMobile)
When you are loading index.html, you are getting file://some_path/..../index.html as your base URL. Any links which will be encountered now own-wards can be resolved in relation to the base URL.
You would know your scenario better. There could be multiple ways in which this can be fixed.
Have a contract with the CMS/Code generator. Links should always be generated either Relative to the base URL or Absolute. The links you are getting in the page are wrong - Link it ideally should be Link or fully qualified like https://www.google.com.
If you want to change the URL then you can use native code to change it after unzipping the content. It will be really straight forward.
If you want to change the URL in browser then you will have to persist the base url and then take care of couple of things:
a. absolute urls - In your case you can just check the window.location.protocol, if it starts with 'http' and then skip it.
b. sub-directories
Here is a small I have written:
Note: I have not tried this code and you might have to change it according to your need.
$(document).ready(function(){
var base_file_name = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
//In index.html (persist this value in native)
var baseUrl = window.location.href.replace(base_file_name, "");
$("a").each(function () {
this.href = baseUrl + this.pathname;
$(this).click(function (e) {
e.preventDefault();
alert(this.pathname);
window.location.href = this.href;
});
});
});
The example you linked should work, make sure you have the <base> set correctly and that you are using the correct string to replace.
Yeah, your going to have to normalize all URL's when your page loads. I can't test with phonegap right now, but your basePath will need to be one of the following:
The file path as you described in your answer (not likely)
window.location.origin (optionally including window.location.pathname)
CODE:
// mini dom ready - https://github.com/DesignByOnyx/mini-domready
(function(e,t,n){var r="attachEvent",i="addEventListener",s="DOMContentLoaded";if(!t[i])i=t[r]?(s="onreadystatechange")&&r:"";e[n]=function(r){/in/.test(t.readyState)?!i?setTimeout(function(){e[n](r)},9):t[i](s,r,false):r()}})
(window,document,"domReady");
domReady(function () {
var anchors = document.getElementsByTagName['a'],
basePath = /* get your base path here, without a trailing slash */;
Array.prototype.forEach.call(anchors, function( anchor ){
anchor.setAttribute('href', basePath + anchor.getAttribute('href'));
});
});
Remove the forward slash from the beginning of your links.
href="content/index2.html">

Reading a AppKey value from web.config in clientside js SPA

I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.
Code for clarity:
define([], function () {
var serviceBaseUrl = 'http://localhost/Service/api/';
var portalPortalUrl = 'http://localhost/Portal';
});
And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.
What I want:
To store them in Web.config file so I can have different configuration for debug and release modes.
I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.
I have only found solutions using ASP.NET ConfigurationManager like so:
function ReadConfigurationSettings()
{
var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
alert(k);
}
Or, for Razor:
#System.Configuration.ConfigurationManager.AppSettings["myKey"]
It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.
If needed, here is my project structure:
- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config
You can use JavaScriptResult
Sends JavaScript content to the response.
Code, Controller Action method
public JavaScriptResult Config()
{
var script = string.Format(#"var configServiceBaseUrl = {0};", ConfigurationManager.AppSettings["var1"]);
return JavaScript(script);
}
In the page header(I would load the file first), You can define:
<script type="text/javascript" src='#Url.Action("Config", "Controller")'></script>
Now configServiceBaseUrl is Global JavaScript variable which you can use anywhere.
So you can use configServiceBaseUrl in url.config.js like
define([], function () {
var serviceBaseUrl = configServiceBaseUrl;
});
Adding to satpal, for SPA application such as angular js
For SPA's, such as angular you can use below code in your index.html as
<script type="text/javascript" src='/Controller/config'></script>

Rewriting Root Directory Path "/" for Javascript

We can modify the document root directory path for PHP using
$_SERVER['DOCUMENT_ROOT'] = "to/some/new/directory";
//Now the "/" which represent the ^(above) path
in .htaccess we have
RewriteBase "/to/some/new/directory"
Now, I need to modify the root directory path to use in javascript. How to do it?
Currently, I am declaring a variable containing static path to the my personalized root directory and using it as
var root = "../to/new/path";
document.location = root+"/somepage.php";
Scenario
I think i should tell a little bit about the scenario, for you guys to catch my idea
Default Web Root Directory
http_docs/
inside it contain a main folder
http_docs/application <-- contains the actual application
http_docs/js <-- contains the script
http_docs/index.html
Now, the application also contains ajax feature for updating, editing, loading new content, or other resources, which if accessed at "/" will represent at /some/path/i/called not /application/some/path/i/called,
To come around this problem
I can define a static variable like
var root = "application/";
and use it somewhere like
$.post(....., function(data) { $(body).append("<img src='"+root+"resources/img1.jpg"); });
But for a single use, defining the path as static, might not be a big deal, but, when the application grows, and certain modification would cause me to change all the paths i give in the js part. I thought, it would be sensible, just like, I do it in PHP, using <img src="/resources/img1.jpg" />
I tried my best to explain this question, if still is not understandable, please community, lets help them understand. I welcome you to edit my question.
EDITED: Trying to answer the updated question
Assuming the JavaScript is called included from the index.html file, if you insert a img tag and use relative urls, they will be relative to the path of the index file. So <img src='application/resources/img1.jpg'> would work just fine. If the script should work for several sublevels (e.g. if the page "application/etc/etc2/somePage.html" needs images from "application/resources/")it may be easier to use absolute urls, and you could include a javascript block on every page generated by php that holds the absolute url to the "root" of the application, like:
<!-- included by php in all html pages, e.g. in defautlHeadter.php -->
<script type="text/javascript">
var rootUrl = "<?= getTheRootUrl() ?>";
</script>
Where getTheRootUrl() is a method or server variable that gives the root url you need. If the url is translated/remapped (by apache etc. outside of what is visible to php) you may need to hardcode the root url in the php method but at least it will be only one file to change if you ever change the root directory.
Then you can use the root url to specify absolute paths anywhere in the application/website using rootUrl + "/some/relative/path" in anywhere in the application.
I once made something like this, to set
window.app_absolute = '<?php echo GetRelativePath(dirname(__FILE__)); ?>'
I also use something like this
static function GetRelativePath($path)
{
$dr = $_SERVER['DOCUMENT_ROOT']; //Probably Apache situated
if (empty($dr)) //Probably IIS situated
{
//Get the document root from the translated path.
$pt = str_replace('\\\\', '/', Server::GetVar('PATH_TRANSLATED',
Server::GetVar('ORIG_PATH_TRANSLATED')));
$dr = substr($pt, 0, -strlen(Server::GetVar('SCRIPT_NAME')));
}
$dr = str_replace('\\\\', '/', $dr);
return substr(str_replace('\\', '/', str_replace('\\\\', '/', $path)), strlen($dr));
}
... Something along those lines, hacked up for demonstration purposes.

Categories