Get relative URL in MVC 4 - javascript

I have a relative path:
~/Content/themes/base/jquery-ui.min.css"
and I have a hidden input:
<input type="hidden" id="siteUrl" value=""/>
In MVC I want to store the fully qualified URL into the hidden field. I have tried:
<input type="hidden" id="siteUrl" value="#Url.RequestContext.HttpContext.Request.MapPath("~/Content/themes/base/jquery-ui.min.css")"/>
and
<input type="hidden" id="siteUrl" value="#HttpContext.Current.Request.MapPath("~/Content/themes/base/jquery-ui.min.css")"/>
But those are both returning a physical path, I need the URL. I have also tried using UriBuilder however this doesn't work for me because while it might work on my localhost it doesn't when I publish it to my IIS server.
I have also tried:
<input type="hidden" id="siteUrl" value="#Url.Content("~/Content/themes/base/jquery-ui.min.css")"/>
but it returns /Content/themes/base/jquery-ui.min.css
and in my MVC controller I tried:
Page.ResolveClientUrl("~/Content/themes/base/jquery-ui.min.css");
which also doesn't do what I need.
Background:
I store that FQ URL into the hidden field and then I access it in JS, in JS when I use a relative url it doesnt know how to use it correctly because with MVC for each link the path changes and it just tacks the relative string on to the end like this:
http://localhost/~/Content/themes/base/jquery-ui.css
If I just remove the ~/ then it works http://localhost/Content/themes/base/jquery-ui.css, but when I click to go to a new link the path is no longer good: http://localhost/newLink/Content/themes/base/jquery-ui.css
The Url on my localhost is http://localhost/Content/themes/base/jquery-ui.css
and on my server its http://server/productName/Content/themes/base/jquery-ui.css I dont want to code for some static name in case the base server url were to change in the future.
So how do I get the fully qualified URL for a relative path?

I'm not sure what issues you were having with UriBuilder, but that's the best method:
#{
var uriBuilder = new UriBuilder(Request.Url);
uriBuilder.Path = Url.Content("~/Content/themes/base/jquery-ui.min.css");
}
<input type="hidden" id="siteUrl" value="#uriBuilder.ToString()"/>
You start with Request.Url, so you don't have to hard code the host. That way, it should work everywhere you deploy it. Then you alter the Path, but you need to use Url.Content to replace the ~ with whatever it should be first.
You might want to actually add your own UrlHelper extension as well:
public static class UrlHelperExtensions
{
public static string AbsoluteContent(this UrlHelper helper, string contentPath)
{
return new Uri(helper.RequestContext.HttpContext.Request.Url, helper.Content(contentPath)).ToString();
}
}

Related

URL path gets converted to query string on jquery

I am trying to get a button to load a new html page in a website I am building with jinja2. The button action in jquery is as follows:
HTML
<input id="str_A" class="form-control-custom" name="str_A" size="30" type="text" placeholder="1st String" />
<input id="str_B" class="form-control-custom" name="str_B" size="30" type="text" placeholder="2nd String" />
<button id="calcdynamic" class="btn btn-lg btn-outline-success">Calculate Edit Distance</button>
JQUERY
$("#calcdynamic").click(function(){
var str_A = $("#str_A").val();
var str_B = $("#str_B").val();
var url1 = "dynamic/"+str_A+"/"+str_B;
window.location. = url1;
});
Now, here's the problem:
I need to pass data in the url path like http://127.0.0.1:5000/dynamic/sgsdgdgsdgd/sdgsdg, not as a query string as http://127.0.0.1:5000/dynamic/?str_A=sgsdgdgsdgd&str_B=sdgsdg. However when I try to reach the url through the jquery call method, I am sent to the query string link, which is a redirectment to the same page I am in at the moment, http://127.0.0.1:5000/dynamic/.
I use flask server (python) and it is configured to redirect like this:
#app.route('/dynamic/')
#app.route('/dynamic/<str_A>/<str_B>')
def dynamic(str_A=None, str_B=None):
At first, I thought this was a problem with flask server, but if I manually type in the URL http://127.0.0.1:5000/dynamic/sgsdgdgsdgd/sdgsdg it works fine.
Can anybody help please, it looks like a simple thing, but I haven't been able to figure out why it happens so far.

How to get the path of selected folder in javascript or node js

I want to get the path of selected folder. Here is my code:
<input style="display:none;" id="fileDialog" type="file" webkitdirectory />
var chooser = document.querySelector('#fileDialog');
chooser.addEventListener("change", function(evt) {
console.log(this.value);
}, false);
chooser.click();
Using this code i'm getting a fakepath.
Is there anyway in node.js,so i can get the path of my selected folder.
I'm using express framework in node.js.
There's no way for you to get the path of the file selected in an input type="file" at all, full stop. Not on the browser, and not transmitted to the server for you to use in Node/Express. That information is simply not available to you. Browsers let you know the name of the file, but that's it.

Liferay portlet: redirect to a new jsp with a js parameter

I'm working on a liferay portlet.
What I want to do is opening a new jsp with sending to it a URL parameter coming from javascript variable. I thought about it and I found two ideas:
1)Send the js variable to the jsp using ajax and then create a render url in jsp with a parameter the value received from js. But how I send js variable to jsp I don't find a good example in the internet.
2)Build the render url in javascript using the received parameter and then redirect from the script itself to the new jsp file using the render url that I found. For this idea I posted this question Liferay portlet: redirect to an other jsp page from javascript but I didn't get solution for it yet.
Has someone a suggestion how I can achieve what I want using one of my ideas or may be an other idea?
I found finally a solution for this problem.
I added in the jsp page a hidden post form that contains just one input and posts to an action method like that:
<portlet:actionURL var="jsVarActionURL" name="jsVarAction"/>
<form:form name="JsVarModel" method="post" modelAttribute="JsVarModel" action="<%=jsVarActionURL.toString() %>">
<form:input id="jsVar" type="text" path="receivedMessage" style="display:none;"/>
<input id="submit" type="submit" value="Add" style="display:none;"></input>
</form:form>
So my want was to for certain condition in javascript I have to send a js variable to new jsp page and open it. So in the script when the condition is valid I set to the input #jsVar the javascript value and I make a virtual click button in the submit button with trigger function of jquery like that:
var jsToJsp="Hello jsp I'm a js variable"
if(/*condition*/)
{
$("#jsVar").val(jsToJsp);
$("#submit").trigger("click");
}
In the controller the action method will receive the value coming from the form input field then it will redirect it to a render method:
#RenderMapping(params={"action=displayPageRender"})
public ModelAndView openUserProfilPage(RenderRequest request,RenderResponse response,Model model)
{
ModelAndView modelAndView= new ModelAndView("display");
modelAndView.addObject("jsVar", request.getParameter("jsVar"));
return modelAndView;
}
#ActionMapping(value = "jsVarAction")
public void sessionKeyActionMethod(#ModelAttribute("JsVarModel")ActionReceiveModel jsVar,ActionRequest actionRequest, ActionResponse actionResponse,Model model)
{
actionResponse.setRenderParameter("jsVar", jsVar.getMessage());
actionResponse.setRenderParameter("action", "displayPageRender");
}
Then I can receive it in display.jsp with ${jsVar} and everything works fine.

Is it possible to have a progress bar on the client side linked to the progress of saveAs()?

I have a controller for uploading a file of any type. A condensed version of it is
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName, string previouslyUploadedFilesJSON = null)
{
// ...... bunch of stuff
try
{
file.SaveAs(newFileServerPathAndName); // Saves file with new file name in assets folder
}
catch
{
throw new Exception("Error when trying to save file to Assets folder.");
}
// ... bunch of other stuff
return View();
}
and the model is like
#using (Html.BeginForm("Index",
"FileUpload",
FormMethod.Post,
new { enctype = "multipart/form-data", #id ="upload-file-form"}))
{
<div>
<label for="file">Upload File:</label>
<input type="file" name="file" id="file" /><br>
<input type="submit" value="Upload" /><img class="loading-icon hidden" src="/ClientPortal/images/loadinggif.gif"/>
<input type="hidden" name="selectedOrgName" class="selectedOrgInput" />
<input type="hidden" name="selectedCatName" id="selectedCatInput"/>
<input type="hidden" name="previouslyUploadedFilesJSON" value="#ViewBag.uploadedFilesJSON" />
<br><br>
</div>
}
and what I'm wondering is whether it's possible for me to have a progress bar on the client's side that is linked to the progress of the saveAs function. In Google Chrome there is already something on the bottom of the browser window like
Uploading (31%)
when uploading the file, so there must be some way to tap into that number on the client side, or there must be some other way using the controller.
The easiest solution is to do this in the browser, since it obviously knows how much data has been sent. Your controller isn't invoked until the upload is complete, so that won't do it, and even if you had the data on the server side then you have to work out how to get the data back to the browser.
jQuery has some support for this, e.g. File upload progress bar with jQuery
You should look into SignalR. We just implemented a progress bar for file uploads in an MVC application and it works great. It's really easy to implement and there are countless tutorials and samples on the web that will show you how to wire it up.

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories