c# Calling Server side method using JQuery - c#

Im trying to call a server method in my aspx.cs to delete all the files in a directory when a user closes the browser.
[WebMethod]
public static void fileDelete()
{
string[] uploadedFiles = Directory.GetFiles(#"C:\Users\Lambo\Documents\Visual Studio 2010\Projects\test\test\testPdfIn");
foreach (string uploaded in uploadedFiles)
{
File.Delete(uploaded);
}
}
======================================================================
EDIT
I've tried the POST method but it still doesn't seem to work. I've changed the URL too.
Over at the client side im using this:
$(function () {
$(window).unload(function () {
alert("Files have been deleted")
jQuery.ajax({ type: 'POST', url: "http://localhost:19642/success.aspx/fileDelete", async: true });
});
});
However it doesnt seem to be working. Are the codes wrong in someway?

To investigate failures of AJAX calls use HTTP debugger (like Fiddler ) to see what requests are made and what responses are received.
My guess is that your Url is wrong and request is made to wrong file. Consider making absolute (or at lest server relative) url.

Related

Ajax Post works locally but not on production server

I ran into an issue where I have an Ajax Post that generates a document serverside. It works great on localhost but when it's published on server side, I receive a 404 in the console.
Here's my code ajax call:
$("#btn1330").on("click", function () {
$("#loading").show();
$.ajax({
method: "POST",
url: "/AdminReports/GenerateForm1330",
data: {
urd: {
"URSID": $(".form-1330-input").val() //this is a string value
}
}
}).done(function () {
$("#loading").hide();
});
});
It is received on controller side (AdminReports) with this:
[HttpPost]
public JsonResult GenerateForm1330(UnlimitedReleaseDocument urd)
{
//my code for generating a document and saving to desktop is here
return Json(true)
}
On localhost, this works as expected with a 200 success, however, when pushed to staging, I see the following error in console:
> POST https://urs-staging.jpl.nasa.gov/AdminReports/GenerateForm1330
> 404 (Not Found)
Any ideas as to why this doesn't work on staging/production? The URL in the console error is exactly the route that it needs to hit so I'm confused! Thanks in advance!

server call from client not working

I have a small angularjs application where I'm trying to call a server side function.
I'm not sure but I feel kind a lost when it comes to use the right url for GET/POST from client to server...But I'm not sure the problem is there..
My angular:
$http.get({
method: 'GET',
url: '/Models/Person/GetTestPersons'
}).then(function successCallback(response) {
alert(response);
}, function errorCallback(response) {
alert("ErrorCallback");
});
My server function (Models/Person.cs):
public static string[] GetTestPersons()
{
return new[]
{
"Person1",
"Person2"
};
}
Now I get to the "alert("ErrorCallback")"
And if I could get this to work.. How do I read the array that is returned?
Error:
GET http://localhost:51203/Views/[object%20Object] 404 (Not Found)
You ought to create a Web API project,
The controller will orchestrate call to your Person model.
A quick starter tutorial is here
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Redirect a page inside a async method

Requirement:
User calls a page and I display page is loading while i execute a method in background and redirect to the url that the method returns.
Tried using async method call in pageload ,pagenotredirected as already loaded.
Tried updating textbox from the async method and call textboxonchange not working as page aleady loaded
Have added the code for ajax per ur suggestion please review
I call a async method inside pageload and in the pageload I display loading message ,after the async methos completes I get a url ,iam trying to redirect to that url but iam unable to do it inside the async as the page is already loaded ,so iam updating an hidden textbox with this url and using the onchange event in that text box and redirecting but still the page is not redirected,can someone please suggest a better way to do this-Thanks
<asp:TextBox runat="server" ID="urlTextBox" Value="" Style="display:none;" AutoPostBack="true" ></asp:TextBox>
$(document).ready(function () {
$('#urlTextBox').change(function () {
var keyword = $("#urlTextBox").val();
if (keyword.length > 0) {
window.location.href = keyword;
}
});
urlTextBox.Text = url;
the urltextbox gets value inside the async method as I process a long running process inside the async to get this url
I have added a js file in which I call the c# method like this
$(document).ready(function () {
$('#outputFromCmdLine').Text = "Loading...";
GetOutputFromCommandLine();
});
function GetOutputFromCommandLine() {
$.ajax({
type: "POST",
url: "Page.aspx/ConvertToBatch", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:true,
success: function (Result) {
window.location.href = Result;
},
error: function (request, status, error) {
alert(request.responseText);
}
});
and the c# method is sync method and returns the url like this
[System.Web.Services.WebMethod()]
public static string ConvertToBatch()
{
some process
return urlstring;
}
I also added the js file name in top of aspx page ,but nothing gets called ,is this the right way to do it
<script type="text/javascript" src="/Scripts/jqueryFile.js"></script>
Instead of calling the async method from inside the page load you should call it using AJAX in JavaScript once the page is loaded. Then you can use the response from the AJAX request to retrieve the URL with which to trigger navigation to.
<script>
$(function()
{
$.ajax(
{
url: "/api/request",
}).done(function(responseUrl)
{
window.location.href = responseUrl;
});
});
</script>
This will wait for the page to be loaded, make some request to the server, and navigate to the response string (expecting the HTTP response body to be a URL).
I think you would use an ASMX web service or better yet an ASP.NET Web API controller to handle the actual request/response.
I know that with Visual Studio 2013 you can create an ASP.NET Web Forms project which includes Web API and configures them automatically to work together. If you are working with an existing project you could add Web API as a NuGet package and add the appropriate plumbing to make it work manually by simply looking at the VS2013 wizard-generated project as an example of how it is done.
EDIT:
It seems you found another way to handle AJAX calls which is using a WebMethod. WebMethods are described in this question.

JSONP no get value result

I'm doing a project for college where one WebSite sends commands to a Windows Forms application. This application is responsible for access to serial port and send and receive commands.
Communication between the Website and the Windows Forms application, I used Web Api, however after publishing, auditioning remembered that the localhost in a C # WebSite. Net's own site and not my Windows Forms application.
I changed the call to the Web Api directly use Ajax and not a controller.
In the examples I found I saw that I use JSONP, but I can not read the results and use it on my website.
The calling code and return seen by Chrome are below
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
jsonpCallback: "cmdTorre",
jsonp: "cmdTorre"
});
}
function cmdTorre(data) {
alert(data);
}
Response Header
Content-Length:10
Content-Type:application/json; charset=utf-8
Date:Tue, 10 Jun 2014 11:18:30 GMT
Server:Microsoft-HTTPAPI/2.0
Response
No Properties
Windows Forms APIController
namespace TCCWindows.Lib
{
public class GPSController : ApiController
{
[HttpGet]
public string Posicao()
{
var coordenada = TCCWindows.FormPrincipal.PegarCoordenadas();
return coordenada.Latitude + "|" + coordenada.Longitude + "|" + coordenada.Altitude;
}
}
}
First, you ajax call looks overly complicated try replacing it with :
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
success: cmdTorre,
error: function(err){
alert("You have a error"+err);
}
});
}
function cmdTorre(data) {
alert(data);
}
Please validate the new code carefully. I just typed it in here so can have errors. If this runs at this point you should probably see the error message. That is because your GPSController doesnt seem to be returning a valid JSONP (or JSON for that matter). Please read up on JSONP for more clarification but, I think if you modify your return statement to make it look like following, it should work. Assuming your controller is actually getting called and your network stuff is working:
return "cmdTorre({\"lat\":"+coordenada.Latitude+" , \"lon\":"+coordenada.Longitude+" });"
Basically your return string should look like following when printed on console:
function cmdTorre({
"lat": 23.34,
"lon":34.23,
"alt":50
});
Again I suggest you check the code I wrote for syntax issues as i just typed it up in here, but it should give you the idea.
So problems were:
The return string you are generating is NOT in JSON format
It is also not wrapped in a function call making it a invalid JSONP too.
Lastly my solution should get your code working and JSONP started but its not the right way to do things. Its more of a ugly hack. Your GPS controller should read the HTTP request for parameter called 'callback' which is a accepted convention for JSONP calls. Then instead of hardcoding the function name in the return statement, you should use the value of this callback parameter. Then you dont need to use a specific function like 'cmdTorre' in your jQuery. Instead a anonymus function like success:function(response){...} will work just fine.
Hope that helps.

Saving changes to a jQuery sortable table

I have a table where the users are allowed to drag and drop rows in the order they want, and then save them. I have no problem with getting the drag and drop part to work. It's the saving I'm having issues with. I'm sending an Ajax call to a web service which will then make the save. I can't seem to actually catch the request in the web service though.
My JavaScript function looks like so:
$(document).ready(
function () {
$(".sortable").sortable({
update: function () {
serial = $('.sortable').sortable('serialize');
$.ajax({
url: "MyWebService.asmx/SortTable",
type: "post",
data: serial,
error: function () {
alert("theres an error with AJAX");
}
});
}
});
});
The JSON string looks fine from what Firebug is showing me. The web service function is like so:
[WebMethod]
public string SortTable(String[] rows)
{
//SaveChanges();
return "Called!";
}
When I put a breakpoint in there, it never gets hit. When there are no arguments in the function though, it will get hit. I've tried replacing "String[]" with "object" and it still doesn't get hit, which I find odd. What is going on here?
You might need to decorate your web service with the [ScriptService] attribute in order to allow client scripts to invoke it. Also if you are sending a JSON request you need to specify the content type. Another remark is about sending the request as an actual JSON object which could be achieved using the JSON.stringify method (maybe the $('.sortable').sortable('serialize') call already does this, I am not familiar, you just need to ensure that the POSTed value looks like this: [ 'row1', 'row2', ... ]):
$.ajax({
url: 'MyWebService.asmx/SortTable',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify([ 'row1', 'row2', 'row3' ]),
error: function () {
alert('theres an error with AJAX');
}
});

Categories