How can I put javascript variable into Url.Action - javascript

I have a post that work well when I run from VS2015 debug:
$("#DisplayChartType").bind("change", function () {
$.post("../Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
iDependOnMyParameter(data);
})
});
But post does not work once I have published to IIS. I tried using ../, / and ~/ in the post but none work. I searched web and found the approach below but I still get ARG1 being sent as a parameter instead of my javascript variable.
$("#DisplayChartType").bind("change", function () {
$.post("#Html.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })".replace("ARG1",$("#DisplayChartType").val()) , function (data) {
iDependOnMyParameter(data);
})
});
How should I do this? I really would like to stay with $.post approach as that works nicely in VS.

You can try this code.
$("#DisplayChartType").bind("change", function () {
var chartType = $("#DisplayChartType").val();
var url="#Url.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })";
$.post(url.replace("ARG1", chartType), function (data) {
iDependOnMyParameter(data);
})
});

So add it to the url
$.post("../Employee/ChangeDisplayChartType?displayChartType=" + encodeURIComponent($("#DisplayChartType").val()), function(){});
or change your original code to GET and the value will be added to the querystring.

You can use window.location.origin or document.location.origin to get the origin of your website, whether running in VS 2015 debug or on IIS.
So instead of doing
$.post("../Employee/ChangeDisplayChartType"
You can try
$.post(document.location.origin + "/Employee/ChangeDisplayChartType"

#OJ Raqueno put me on the right path.
At top of script I now declare "myPath". My website URL ends with "secure" so this test gives me the right path:
var myPath = document.URL;
if (!myPath.endsWith("secure")) {
myPath = "";
}
Then I do this:
$("#DisplayChartType").bind("change", function () {
$.post(myPath + "/Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
alert($("#DisplayChartType").val());
iDependOnMyParameter(data);
})
});

Related

How do i get the relative path with JQuery?

I recognize that this has been asked before but I have yet to find an answer that is working for me. I'm basically following a solution for keeping an ASP session alive I found at dotnetcurry by Malcom Sheridan.
I have the following JQuery defined on the masterpage of an asp.net site. As the default page is on the same level, it has no problems making the serverside call every 7 seconds; however, when I navigate to another page, deeper in the file structure, the ajax post starts to fail.
var interval;
$(function () {
setheartbeat();
});
function setheartbeat() {
interval = setInterval("heartbeat()", 7000);
}
function heartbeat() {
$.post("./SessionHeartbeat.ashx", null, function (data) {
})
.done(function () {
alert('done');
})
.fail(function () {
clearInterval(interval);
alert('Failed to keep session alive. Please close the browser and log back in.');
});
}
Besides the sample from above, I've already tried, with none of them working:
$.post("/SessionHeartbeat.ashx", null, function(data) {...}
$.post(window.location.pathname + "/SessionHeartbeat.ashx", null, function(data) {...}
$.post(vpath + "/SessionHeartbeat.ashx", null, function(data) {...} where vpath = "<%=ApplicationVirtualPath %>"; after I've included the System.Web.Hosting.HostingEnvironment namespace
Anyone have any thoughts?
Thank you

How to change settings with Uploadify after control has already been created

I initialize Uploadify using the following code:
$('#file1').uploadifive({
'buttonClass': 'upload-btn',
'uploadScript': '/Upload/',
'fileObjName': 'files',
'fileType': 'text/xml',
'formData': { 'uploadType': 'Crew' },
'onUploadComplete': function(file, data) {
var results = $.parseJSON(data);
if (results.error) {
var info = file.queueItem.find('span.fileinfo');
if (info) info.text(' - ' + results.error);
return;
}
window.location.href = '#Url.Content("~/Upload/Checkdata/")' + results.id;
}
});
This works, however I need to modify the formData property when a radio checkbox changes. So, I've tried this:
$('input[name=UploadType]:radio').change(function () {
$('#file1').uploadifive({ 'formData': this.value });
});
However, when that code runs, it breaks the Uploadify control (it now no longer uploads anywhere). I'm guessing because it completely re-initializes the control with all new settings.
How can I update just this one setting? I've read the Uploadify docs and none of them say anything about updating settings; just initializing and calling methods. Thanks!
I've figured out one solution, but not sure if it's the right way to do things (i.e., it might break in future versions of Uploadify).
Basically, it appears you can keep a reference to your configuration around, and update that object at any time:
var uploadifySettings = {
'buttonClass': 'upload-btn',
'uploadScript': '/Upload/',
'fileObjName': 'files',
'fileType': 'text/xml',
'formData': { 'uploadType': 'Crew' },
'onUploadComplete': function(file, data) {
var results = $.parseJSON(data);
if (results.error) {
var info = file.queueItem.find('span.fileinfo');
if (info) info.text(' - ' + results.error);
return;
}
window.location.href = '#Url.Content("~/Upload/Checkdata/")' + results.id;
}
}
$('input[name=UploadType]:radio').change(function () {
uploadifySettings.formData.uploadType = this.value;
});
$('#file1').uploadifive(uploadifySettings);

Reload the page using sammy.js

I am using sammy.js for single page application in asp.net mvc. Everything is fine, but I am facing one problem which is that I can not reload the page. For example When I am in the dashboard my URL is
http://localhost:1834/#/Home/Index?lblbreadcum=Dashboard
layout.cshtml
<script>
$(function () {
var routing = new Routing('#Url.Content("~/")', '#page', 'welcome');
routing.init();
});
</script>
routing.js
var Routing = function (appRoot, contentSelector, defaultRoute) {
function getUrlFromHash(hash) {
var url = hash.replace('#/', '');
if (url === appRoot)
url = defaultRoute;
return url;
}
return {
init: function () {
Sammy(contentSelector, function () {
this.get(/\#\/(.*)/, function (context) {
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run('#/');
}
};
}
I want to reload the page by clicking the dashboard menu/link. But click event not firing because link is not changing. But if I want to go another page then it is fine. Please help me out. Thanks.
I think you have to append the same partial again. You can't "update" the partial in that meaning.
As you say in your post, when you click another link and then back again it works.
That's what you'll have to do. Append the same page/partial again, by doing that you clear all variables and recreate them, by that simulating a refresh.
EDIT: Added example
Observe that I didn't copy your code straight off but I think you'll understand :)
And I don't use hash (#) in my example.
var app = Sammy(function () {
this.get('/', function (context) {
// context is equalient to data.app in the custom bind example
// currentComponent('home'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
this.bind('mycustom-trigger', function (e, data) {
this.redirect('/'); // force redirect
});
this.get('/about', function (evt) {
// currentComponent('about'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run();
// I did an easy example trigger here but I think you will need a trigger on your link-element. Mayby with a conditional check wheter or not to trigger the manually binding or not
$('.navbar-collapse').click(function () {
app.trigger('mycustom-trigger', app);
});
Please read more about events and routing in sammy.js
Good luck :)
An easier and cleaner way to force the route to reload is to call the Sammy.Application refresh() method:
import { sammyApp } from '../mySammyApp';
const url = `${mySearchRoute}/${encodeURIComponent(this.state.searchText)}`;
if (window.location.hash === url) {
sammyApp.refresh();
else {
window.location.hash = url;
}

Multiple routes not working correctly in backbone.js

I'm trying to create a basic webapp that displays images when a specific URL is reached. In this case, I'm using backbone.js's hash system.
I'm trying to make it so that when "www.website.com/index.html#1" is reached, the first image is displayed using some JavaScript that I have. I also need it so that if "www.website.com/index.html#1/#3/#5" is reached, the first, third, and fifth image is displayed. I know that I have to use multiple routes to do this, but I'm not sure how.
I have one working route for the first image that works awesomely. I just don't know how to adapt it so that it works with multiple routes.
Here's the working hash -
<script>
$(function(){
var hideOne = function () {
//alert("hideOne");
var elem = document.getElementById("one");
elem.className = "hide";
};
var Workspace = Backbone.Router.extend({
routes: {
"test":"test",// #test
},
test: hideOne
});
var router = new Workspace();
Backbone.history.start();
});
</script>
It's awesome, it works, it doesn't even refresh the page. But when I try to add another route to that, it all fails. Like, if I added a "test1":"test1" under the "test":"test", the original "test":"test" won't work anymore(neither will the new one, of course).
I've even tried copying+pasting that entire block of code and trying to make a whole new route block of code. That doesn't work either. I'm really stumped here.
Any suggestions would be awesome.
Thanks
You should limit the scope of your first use case. Don't depend on external functions for now. Do something like
routes: {
"test":function(){
alert("test");
},
"test2":function(){
alert("test2");
}
},
Then change to
routes: {
"test":"test",
"test2":"test2"
},
{
test: function(){
alert("test");
},
test2: function(){
alert("test2");
}
}
Read more: http://mrbool.com/backbone-js-router/28001#ixzz3ANyS0hkR
Once you have that working, then start working on DOM manipulation.
routes: {
"?*:queryString": 'showImages'
},
showImages: function(queryString) {
console.log(queryString); // #1#3#5
}
You can use the route "?*:queryString" to match this URL "www.website.com/index.html#?#1#3#5".
The functions "showImages" will be called and passing the value #1#3#5 in the queryString param.
So from other questions posted on StackOverflow, and some that I posted myself, some great users have helped me out and I've solved it.
Here's the code that I have to use -
<script>
$(function(){
var hideMany = function () {
var toHide = [].slice.call(arguments);
toHide.forEach(function (id) {
if(id === null) { return }
var elem = document.getElementById(id);
if(elem) {
elem.className = "hide";
}
});
};
var Workspace = Backbone.Router.extend({
routes: {
"hide(/:a)(/:b)(/:c)" : "test"
},
test: hideMany
});
var router = new Workspace();
Backbone.history.start();
});
</script>
So when you type "www.website.com/index.html#hide/ID1/ID2/ID3", it'll hide the elements with the IDs that you typed in.
I don't fully understand it, but I'm working on breaking it down and figuring out how it works. Thanks for all the help, guys!

$.get() does not work?

UPDATED!!
The code after
$.get(url, { id: id, action: action }, function(data) {
does not fire? Complete method below.
function modifyPermit(id, action) {
var url = "ajax/permit_modify.aspx";
$.get(url, { id: id, action: action }, function(data) {
if (data == "SUCCESS") {
// Update page
$.get("ajax/permit_getall.aspx", function (data) {
$("#ctl00_ContentPlaceHolder1_permitList").html(data);
}).error(function(err) {
alert(err);
});
} else {
alert(data);
}
});
}
Using .Net.
Regards,
Robert
You seem to be using a wrong variable for the url here (you defined url_mod but used url in your AJAX request):
var url_mod = "ajax/permit_modify.aspx?id=" + id + "&action=" + action;
$.get(url, function(data) {
which should should become:
var url = "ajax/permit_modify.aspx?id=" + id + "&action=" + action;
$.get(url, function(data) {
Also instead of manually having to call the encodeURIComponent function for each parameter (which by the way you forgot to do in your second AJAX request) I would recommend you using the following construct:
var url = 'ajax/permit_modify.aspx';
$.get(url, { id: id, action: action }, function(data) {
This way jQuery will take care of generating the properly encoded url. The same concept could be applied in your first AJAX request. Notice how you could pass as second parameter to the $.get function key/value pairs that jQuery will use to construct the proper url.
UPDATE:
After having an offline chat with the OP it turned out that the problem was not related to the AJAX code shown in his question but rather with the way he was calling the modifyPermit function. It was inside the onclick handler of a button without returning false. This in turn triggered a full postback to the server leaving no time for the AJAX request to execute. The correct solution was to return false to prevent the default action of the button:
onclick="modifyPermit(1,'a'); return false;"
Fix found by #darin which tuned out to be simple: just add return false; after the method call on the button.
modifyPermit(1,'a'); return false;
Many thanks to Darin for all the time and effort he put in the helping me solve this issue. Could not have don it without you!
/Bob

Categories