asp.net mvc url action in javascript code and IIS publish - javascript

I am developing asp.net mvc project. I have a javascript object that sends query to controller action. in cshtml file I can use #Url.Action("get", "product") so when I publish the web site, url action is rendering by location url. If I publish it http://localhost/App1/, the action url is like this http://localhost/App1/product/get or I can publish it another directory like http://localhost/App2/ and so on.
But I have an issue in javascript code.
sample.js
function query(){
var url = "/product/get";
// send query this url
}
When I publish the project in http://localhost/App1/ url (APP1 folder), javascript query is sending request to http://localhost/product/get , but it should be like this http://localhost/App1/product/get
I can not use #Url.action() razor expression. How can I solve this issue?

You can place root level appPath variable in your _layout.cshtml
<script type="text/javascript">
var appPath = #Url.Content("~/");
</script>
Then in your query
function query(){
var url = appPath +"/product/get";
}

I send the url as a parameter from the View to the javascript function which is written in a js file. This saves you the trouble of creating a url in js and you can use you razor expression for the same.
So your function becomes:-
function query(url){
//var url = "/product/get";
// send query this url
}

Related

How can I get the url working from js html builder in Django?

I am currently building a web app using Django.
I've build a calendar using JS and I am building HTML basically from the Js File.
I am trying to include hrefs in each calendar day. For example :
{% url 'calendarDay' day=28 month=12 year=2016 %} is what should have for 28/12/2016 date.
If I try to go to this url from anywhere else in my templates it works. For some reason it is not working when I pass the html from js.
This is what I have in my urls:
url(r'^calendar/$', views.calendar, name='calendar'),
url(r'^calendar/(?P<day>\w+)/(?P<month>\w+)/(?P<year>\w+)/$',views.calendar, name = 'calendarDay'),
This is my js builder function (the part that builds the previous month's days):
if (FirstDay.getDay()==0){
for (var i=LastMonthDays-5; i <= LastMonthDays; i++) {
href="<a href=\"{% url 'calendarDay' day="+i+" month="+(pastMonth.getMonth()+1)+" year="+pastMonth.getFullYear()+" %}\">"
html +=href+ "<li>"+(i)+"</li></a>";
}
}
This is how the html file looks like when I inspect the page:
<li>28</li>
For some reason the urls that it gets is: http://127.0.0.1:8000/calendar/%7B%%20url%20'calendarDay'%20day=28%20month=12%20year=2016%20%%7D
And ofcourse I get the following error:
The current URL, calendar/{% url 'calendarDay' day=28 month=12 year=2016 %}, didn't match any of these.
What might be the issue here?
Templatetags will be rendered in server side, before javascript. you should create a javascript function for generating your calendar urls.

Read in javascript a spring controller model

I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.

Calling python function in server from local machine using angularjs

I am having problem in calling a python function with angularjs $http request.
I am having a python function which is on server like this
import cgi, cgitb
data= cgi.FieldStorage()
name = data.getvalue("name");
age = data.getvalue("age");
def printinfo( name, age ):
print "Name: ", name
print "Age ", age
return name,age
and i've also included cgi and my javascript code is
angular.module('app1',[])
.controller('ctrl',['$scope','$http' ,function ($scope,$http) {
$scope.bin = 'examp';
$scope.go = function () {
var url = "http://localhost/dump/test/test.py";
var bad =$http({
url :url ,
method:'POST',
data:{"name":"kumar" , "age":21}
}).success(function(data){
alert("working");
});
}
}])
and my javascript code is able to make a call to http://localhost/dump/test/test.py but it is shown as a document even when i included cgi in it ..
Please guide me and also can you guys tell me is it the right way to send the values to server ie can i invoke the function print info by just sending name and age or should i send the function name too. If yes let me know how can i pass it ..
Thanks in advance..
May be your webserver do not know how to handle .py files. You need to configure webserver to handle python. Try the below if it is not configured.
https://www.linux.com/community/blogs/129-servers/757148-configuring-apache2-to-run-python-scripts
But a more good approach is to create a web app using some python framework and expose urls via a web server. If you are interested in that then I would recommend you to learn flask python framework.

Pass Javascript Variable into createlink method call Grails

var search= document.getElementById('appMenu').value
document.location.href= '${createLink(controller: 'application' , action:'ajaxAppSearch', params: ['query': search])}'
The element appMenu is a text field, so I am getting the value that the user enters into the text box to pass into a search controller. However, it keeps telling me that the params query is null. It seems that search isn't being passed into the create link method. Anyone have a suggestion?
Grails (controllers, GSP and tags, etc) are working on server side. JavaScript on client side. And this link is prepared before sending data to browser, and before JavaScript can pass its variable into GSP tag.
But you can prepare base link on server side, and add extra parameter on client side, by using javascript, like:
var search= document.getElementById('appMenu').value;
document.location.href= '${createLink(controller: 'application' , action:'ajaxAppSearch')}?query=' + escape(search);

How to open a window using Javascript from ASP.NET MVC?

I am writing a tiny MVC app that is a utility to simulate the actions of getting an id from a portal and setting it in a database for another app to obtain while this app is open. I attempted to write it using ASP.NET MVC to "get my feet wet." In it, I am attempting to use the JavaScriptResult (DESPITE all the warnings) to execute Javascript's window.open function but I get only a file dialog that is acting like the FilePathResult - it displays a dialog box asking if I want to save my file which is the name of the ActionEResult. How do I do this?
public JavaScriptResult SessionTransferDesktop(string PortalUserId)
{
/// .... Call Oracle SP to set token
// Redirect to RON Scheduler
string js = "window.open('/RONSchedulerMVC/default.aspx?p_token=' + portalToken);";
// string js ="window.open('http://microsoft.com')";
return JavaScript(js);
}
public ActionResult SessionTransferDesktop(string PortalUserId)
{
/// .... Call Oracle SP to set token
// build url and redirect
var uriBuilder = new UriBuilder("http://example.com");
uriBuilder.Path = "/RONSchedulerMVC/default.aspx";
uriBuilder.Query = "p_token=" + Url.Encode(portalToken);
return Redirect(uriBuilder.ToString());
}
You are getting the file result because your browser is requesting something and getting content-type:application/javascript back.
The easiest way to get this to work is to simply make the route redirect the response to the portal. You can then just call window.open directly on said route and profit.

Categories