jQuery calls asmx web method multiple times - c#

I have a jQuery method that calls a .asmx web service. The jQuery method only executes one time but the web service executes multiple times.
this is the jQuery code that call the web service
// Expand copy to group modal groups
$(".groupZones .expand").live('click', function() {
$(this).siblings('.contract').show();
$(this).css('display', 'none');
$(this).parent().parent().siblings('.groupDetails').css('display', 'block');
$(this).parent().parent().siblings('.groupDetails').find('ul.device').find('ul .list').after('');
var cwpUserId = $('#ctl00_cphBody_hfCwpId').val();
var groupId = $(this).parent().siblings('.add').find('input').val();
sortOn = "Location";
var mode = "dayparts";
var groupUl = $(this).parent().parent().siblings('.groupDetails').find('ul').find('ul li.head');
var groupDetails = $(this).parent().parent().siblings('.groupDetails');
//Get the zone details..
// Load.
$.ajax({
type: "POST",
url: "ajax/DaypartMessagingGroups.asmx/GetDetailsForCopyToGroup",
data: "{'groupId':" + groupId + ",'cwpUserId':" + cwpUserId + ",'pageNum':0,'pageSize':5, 'sortOn':'" + sortOn + "','sortDirection':'" + sortDirection + "','mode':'" + mode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//$(btn).parents("ul.list-group-zones").children("li:.head").after(msg.d);
$(groupUl).after(msg.d);
$('.location').find('.contract').hide();
var copyZonePerPage = 5;
//var copyZoneItemsCount = $(groupUl).siblings('#hfAllGroupZones').val();
var copyZoneItemsCount = $('#hfAllGroupZones').val();
var copyZonePages = Math.ceil(copyZoneItemsCount / copyZonePerPage);
var copyZoneHtml = '';
var copyZoneCurLink = 0;
var current_copyzone_pagination_set = 1;
var num_of_pagination_shown = 0;
alert('Line 2113 CBG');
if (copyZonePages > 20) {
//var pagesAdded = (parseInt(current_copyzone_pagination_set) - 1) * 10;
while (num_of_pagination_shown < 20) {
copyZoneHtml += '<a class="page_link_clicked" longdesc="' + copyZoneCurLink + '">' + (copyZoneCurLink + 1) + '</a>';
copyZoneCurLink++;
num_of_pagination_shown++;
}
copyZoneHtml += '<a class="page_link" id="btnNextZoneSet" longdesc="' + copyZoneCurLink + '">...</a>';
}
else {
while (copyZonePages > copyZoneCurLink) {
copyZoneHtml += '<a class="page_link_clicked" longdesc="' + copyZoneCurLink + '">' + (copyZoneCurLink + 1) + '</a>';
copyZoneCurLink++;
}
}
$(groupUl).parent().parent().find('ul li.footer').html(copyZoneHtml);
$('.page_link_clicked[longdesc=0]').addClass('current');
},
error: function(err) {
var err = eval("(" + err.responseText + ")");
if (ShowModalLogin(err.ExceptionType)) {
alert("An error occurred.");
}
}
});
});
after doing more test i see that post is actually being repeated numberous times.

http://api.jquery.com/live/ states that
To stop further handlers from executing after one bound using .live(), the handler must return false. Calling .stopPropagation() will not accomplish this.
I am not sure if that applies here, but you could add a
return false;
at the end of your click handler and see if it works.

Related

ASP.NET C# - running a .exe process and reloading the page when it's done

I'm building an application to configure some software components from a web GUI.
For one of my configuration components, I'm loading an executable to pick an sftp folder. This sftp path is stored together with other variables in a json file, which is then displayed in the input fields.
The cshtml code:
<button class="btn btn-primary" onclick="browseSftp()">Select SFTP folder</button>
function browseSftp() {
window.$.ajax({
type: "POST",
url: "/BackupConfiguration?handler=BrowseSftp",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
window.$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
autoBackup: $('input[name="FormData.autoBackup"]:checked').val(),
backupTime: $('#FormData_backupTime').val(),
keepAllBackups: $('input[name="FormData.keepAllBackups"]:checked').val(),
backupsKept: $('#FormData_backupsKept').val(),
hostName: $('#FormData_hostName').val(),
hostKey: $('#FormData_hostKey').val(),
port: $('#FormData_port').val(),
username: $('#FormData_username').val(),
password: $('#FormData_password').val(),
remoteFolder: $('#FormData_remoteFolder').val(),
localFolder: $('#FormData_localFolder').val(),
isLocal: $('input[name="FormData.isLocal"]:checked').val(),
}),
success: function (response) {
alert("success");
}
});
};
in my cshtml.cs code:
public void OnPostBrowseSftp([FromBody] FormData formData)
{
//string[] args = { FormData.autoBackup, FormData.backupTime, FormData.keepAllBackups, FormData.backupsKept, FormData.hostName, FormData.hostKey, FormData.port, FormData.username, FormData.password, FormData.remoteFolder, FormData.localFolder, "TRUE" };
string[] args = {FormData.hostName, FormData.username, FormData.password};
if(formData.autoBackup == null)
{
formData.autoBackup = "false";
}
if(formData.keepAllBackups == null)
{
formData.keepAllBackups = "false";
}
var process = System.Diagnostics.Process.Start(_browseSftpScript, formData.hostName + " " + formData.username + " " + formData.password + " " + formData.autoBackup + " " + formData.backupTime + " " + formData.keepAllBackups + " " + formData.backupsKept + " " + formData.port + " " + formData.isLocal + " " + _jsonPath);
process.WaitForExit();
Response.Redirect("/backupConfiguration");
}
Just re initializing the page with the onGet function would cause the fields to be populated, but somehow this is not done, only if I manually select another page and go back it's done:
public void OnGet()
{
if (HttpContext.Session.GetString(SettingName) == null || HttpContext.Session.GetString(SettingName) != "AlreadyLoaded")
{
HttpContext.Session.SetString(SettingName, "AlreadyLoaded");
if (System.IO.File.Exists(_systemSettingJsonPath))
{
FormData = SettingsService.GetData<FormData>(_systemSettingJsonPath);
SettingsService.SaveData(FormData, _jsonPath);
}
else
{
FormData = SettingsService.GetData<FormData>(_jsonPath);
}
}
else
{
FormData = SettingsService.GetData<FormData>(_jsonPath);
}
}
If I have a look at my logs, I think it's because the onGet function is called before the browseSftp request is finished.
2021-11-25 17:31:22.922 +01:00 [Microsoft.AspNetCore.Routing.EndpointMiddleware] [INF] Executed endpoint '/BackupConfiguration'
2021-11-25 17:31:22.922 +01:00 [Microsoft.AspNetCore.Hosting.Diagnostics] [INF] Request finished HTTP/1.1 POST http://localhost:5000/BackupConfiguration?handler=BrowseSftp application/json;+charset=UTF-8 228 - 200 - text/html;+charset=utf-8 705431.7372ms
I would expect that this would cause the process to be finished, and therefore the request to be done:
process.WaitForExit();
Response.Redirect("/backupConfiguration");
So to put it short, my goal is to trigger a reload of the page, after the process is finished.
Thanks for your input on this !

how to allow file download in asp.net from dynamically generated table

I am using elasticsearch to query in index of PDFs on a asp.net mvc app. When I get the result I would like the user to be able to click the returned filename to download that file. Researching how to enable this functionality has returned plenty of results but none seem to work for me. I would simply like the user to be able to click on the filename and have the file download for them. I am using the below code.
To generate the dynamic table with search results
var row = $("<tr><th>" + "Search Results" + "</th><th>" + "File Name" + "</th>");
$("#myTable").append(row);
for (var i = 0; i < response.datasend.length; i++) {
var pos = response.datasend[i].Attachment.Content.indexOf(obj.searchterm);
var row = $("<tr><td>" + response.datasend[i].Attachment.Content.slice((pos - 100), (pos + 100)) + "</td><td><a href=# id=fileName>"
+ response.datasend[i].filename + "</a></td></tr>");
$("#myTable").append(row);
}
To detect the requested filename and call the function to start the download process
var table = document.getElementById("myTable");
table.addEventListener("click", function(e) {
if (e.target && e.target.id == "fileName")
{
var apiUrl = "/AllSearch/Download";
var obj = {};
obj.searchterm = e.target.innerHTML;
var params = e.target.innerHTML;
$.ajax({
contentType: 'application/json',
url: apiUrl,
dataType: "json",
data: {fileName: obj.searchterm},
success: function(data) {
alert("success");
},
error: function (xhr, err) {
alert("ready state: " + xhr.readyStat + " " + xhr.status);
}
});
}
});
To start download the file
public ActionResult Download(string fileName)
{
string filename = fileName;
string filePath = #"C:;at\to\file\Documents\" + fileName;
byte[] filedata = System.IO.File.ReadAllBytes(filePath);
string contentType = MimeMapping.GetMimeMapping(filePath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
The Download function is from Returning a file to View/Download in ASP.NET MVC but it returns an error when I run it. Not sure what I am missing here. Any help is appreciated

Calling Web Method in Web Service

Basically I am trying to consume web service methods in JavaScript class in ASP.NET. So here is the methods in my web service:
[WebMethod]
public DataSet GetFireStation()
{
SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
string select = "select * from dbo.FireStation ";
sqlConnection1.Open();
// Create an Adapter
SqlDataAdapter da = new SqlDataAdapter(select, sqlConnection1);
// Create a New DataSet
DataSet ds = new DataSet();
// Fill The DataSet With the Contents of the Stock Table
da.Fill(ds, "FireStation");
sqlConnection1.Close();
// Now Return ds which is a DataSet
return (ds);
}
Then here is my HTML code which call the function in JavaScript class:
case "Accident":
if (type == 'Accident') {
symbol = new esri.symbol.PictureMarkerSymbol('img/Accident.gif', 25, 20);
htmlStr = htmlStr + "<input type='button' id='btnHosPoint' class='infoTempButton infoTempOrange' title='To Hospital' value='' onclick='getSafetyCoordXY(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ", " + '\"' + type + '\"' + ");connectNearestRoute(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />"
+ "<input type='button' id='btnClinicPoint' class='infoTempButton infoTempOrange' title='To Clinic' value='Clinic' onclick='connectNearestClinic(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />"
+ "<input type='button' id='btnFirePoint' class='infoTempButton infoTempOrange' title='Nearest Fire Station' value='FS' onclick='ConnectNearsetFireStation(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />"
+ "<input type='button' id='btnPolicePoint' class='infoTempButton infoTempOrange' title='Nearest Police Station' value='Police' onclick='ConnectNearsetPolice(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />";
var point = new esri.geometry.Point({ "x": $(this).find("actualX").text(), "y": $(this).find("actualY").text(), "spatialReference": { "wkid": 3414 } });
var graphic = new esri.Graphic(point, symbol);
map.graphics.add(graphic);
var infoTemplate = new esri.InfoTemplate();
infoTemplate.setTitle("<img src='img/Accident.gif' style='width:25px; height:25px;'/> " + type);
infoTemplate.setContent("Information: " + incidentMessage + "</br>" + "</br>" + htmlStr);
graphic.setSymbol(symbol);
graphic.setInfoTemplate(infoTemplate);
incidentLocation.push(graphic);
htmlStr = "";
}
break;
And here is my function in JavaScript class which retrieve data from database which will pass thru the web service method:
EDIT
function ConnectNearsetFireStation(x, y) {
map.infoWindow.hide();
//map.infoWindow.resize(350, 120);
var Fire = [];
var FireStationPointGraphic = [];
$.ajax({
'type' : 'GET',
'url' : 'http://localhost/SgDataService.asmx' + 'GetFireStation',
'success' : function(results){
$.each(GetFireStation(), function () {
var name = $(this).find("ID").text();
firestation = $(this).find("Name").text();
address = $(this).find("Address").text();
postal = $(this).find("PostalCode").text();
coordX = $(this).find("X").text();
coordY = $(this).find("Y").text();
// Compute Distance
var IncidentPoint = new esri.geometry.Point({ "x": x, "y": y, "spatialReference": { "wkid": 3414 } });
var FireStationPoint = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
var distance = esri.geometry.getLength(IncidentPoint, FireStationPoint);
Fire.push(distance);
var point = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
var symbol = new esri.symbol.PictureMarkerSymbol('/SAFETY_AT_SG/Images/Features/FireStation.gif', 25, 25);
var PointGraphic = new esri.Graphic(point, symbol);
var infoTemplate = new esri.InfoTemplate();
infoTemplate.setTitle("<img src='/SAFETY_AT_SG/Images/Features/PoliceStation.png' style='width:25px; height:25px;'/> " + firestation);
infoTemplate.setContent("<b>FireStation: </b>" + firestation + "<br/>"
+ "<b>Address: </b>" + address + "<br/>"
+ "<b>PostalCode: </b>" + postal + "<br/>"
);
PointGraphic.setSymbol(symbol);
PointGraphic.setInfoTemplate(infoTemplate);
//Store PoliceStation To Array
FireStationPointGraphic.push(PointGraphic);
//OneMap.map.graphics.add(PointGraphic)
}
);
}
});
var minDist = Math.min.apply(null, Fire); //Get Smallest Distance
for (var i = 0; i < Fire.length; i++) {
if (minDist == Fire[i]) {
var myX = FireStationPointGraphic[i].geometry.x;
var myY = FireStationPointGraphic[i].geometry.y;
OneMap.map.graphics.add(FireStationPointGraphic[i]);
RouteU(x + ',' + y + ";" + myX + ',' + myY);
break;
}
}
}
However, when I try to call the GetFireStation() in conenctNearestFireStation(), it told me an error message which is GetFireStation is not defined. I wonder why is it so. Do I need to add any reference to web service if my JavaScript class is calling the methods inside?
Thanks in advance.
I think the code should end up something like this
function ConnectNearsetFireStation (x, y){
var Fire = [];
var FireStationPointGraphic = [];
var setRoute = function (){
var minDist = Math.min.apply(null, Fire); //Get Smallest Distance
for (var i = 0; i < Fire.length; i++) {
if (minDist == Fire[i]) {
var myX = FireStationPointGraphic[i].geometry.x;
var myY = FireStationPointGraphic[i].geometry.y;
OneMap.map.graphics.add(FireStationPointGraphic[i]);
RouteU(x + ',' + y + ";" + myX + ',' + myY);
break;
}
}
}
var processFireStations = function (allFireStations){
$.each(allFireStations, function (){
var name = $(this).find("ID").text();
firestation = $(this).find("Name").text();
address = $(this).find("Address").text();
postal = $(this).find("PostalCode").text();
coordX = $(this).find("X").text();
coordY = $(this).find("Y").text();
// Compute Distance
var IncidentPoint = new esri.geometry.Point({ "x": x, "y": y, "spatialReference": { "wkid": 3414 } });
var FireStationPoint = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
var distance = esri.geometry.getLength(IncidentPoint, FireStationPoint);
Fire.push(distance);
var point = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
var symbol = new esri.symbol.PictureMarkerSymbol('/SAFETY_AT_SG/Images/Features/FireStation.gif', 25, 25);
var PointGraphic = new esri.Graphic(point, symbol);
var infoTemplate = new esri.InfoTemplate();
infoTemplate.setTitle("<img src='/SAFETY_AT_SG/Images/Features/PoliceStation.png' style='width:25px; height:25px;'/> " + firestation);
infoTemplate.setContent("<b>FireStation: </b>" + firestation + "<br/>"
+ "<b>Address: </b>" + address + "<br/>"
+ "<b>PostalCode: </b>" + postal + "<br/>"
);
PointGraphic.setSymbol(symbol);
PointGraphic.setInfoTemplate(infoTemplate);
//Store PoliceStation To Array
FireStationPointGraphic.push(PointGraphic);
//OneMap.map.graphics.add(PointGraphic)
});
// Once the $.Each is over, map the route
setRoute();
};
var getFireStations = function (){
$.ajax({
'type' : 'GET',
'url' : 'http://localhost/SgDataService.asmx' + 'GetFireStation',
'success' : processFireStations
});
};
map.infoWindow.hide();
//map.infoWindow.resize(350, 120);
getFireStations(); // start everything
}
JavaScript is executed on the client. Your web method is available on the server. You need to make an ajax call to execute the webmethod and return the results to the client
This means that you need to write an additional javascript function. JQuery will really help you with this as it provides some simplified, cross-browser compatible methods to make ajax calls.
// $ is a shortcut for jQuery
$.ajax({
'type' : 'GET',
'url' : yoururl + 'GetFireStation'
'success' : function(results){
// do stuff
}
}});
Please note:
AJAX makes an asynchronous call, which means that you may have to
rethink how you've written your javascript functions so far
Update
Lots more info and examples on the jQuery API page for ajax

Ajax webservice does not work in remote machines

I have a webservice written in c# used by a Windows phone cliente and working.
So i develop a html5/jquery to use that same asmx service and Works!
When i try to access this html page from a remote machine(other than the host for the pages and servisse) it fails.
is there any special configuration for this scenario?
The only difference is, changed from localhost in the address of the ajax call to webservice to the fixed ip of the host, same i did to publish to the phone device.
Here is the code
$.ajax({
url: "http://localhost:8000/services/webservice.asmx/RetornaPedidoPorMesa",
type: "POST",
dataType: "text",
data: { NumeroMesa: parseInt(querystring("numeroMesa")),
CodigoSeguranca: parseInt(querystring("codigo")) },
success: function (response) {
var xml = $(response);
if (xml.find("Retorno").text() != "") {
var list = $("#pedido").find('ul');
$("#ulPedido li").remove();
list.append("<li>Voçê não tem permissão para acessar o pedido</li>");
} else {
if (xml.find("Total") != "") {
var list = $("#pedido").find('ul');
$("#ulPedido li").remove();
list.append("<li>" + "Mesa " + querystring("numeroMesa") + " - " + "R$ " + xml.find("Total").first().text() + "</li>");
}
if (xml.find("Items") != "") {
if (xml.find("RetornoItems") != "") {
var list = $("#produtos").find('ul');
$("#ulProdutos li").remove();
$(xml.find("RetornoItems")).each(function myfunction() {
if (parseInt($(this).find("Quantidade").first().text()) > 0)
list.append("<li>" + $(this).find("Descricao").text() + "<div style='float:right\;margin-left:30px;margin-top:10px'>" + parseInt($(this).find("Quantidade").first().text()) + " x R$ " + $(this).find("ValorUnitario").first().text() + " = R$ " + $(this).find("Total").first().text() + "</div></li>");
});
}
}
}
},
error: function (response) {
alert("erro de acesso ao serviço.");
}
});
Any help? thanks in advance...

Map 2 properties for same data base column in Entity Framework

I am working on EF 4.1 code first development with MVC and c#.
This is my Requirement:
Is there any way to map 2 properties of my model class for same database column ?
B'cos I am having data retrieval issue like below.
Currently mapped property for db column having some complex calculation.
So that When I call it from my UI as a ajax call it retrieves calculated value as 0.0, b'cos of that calculation delay (when i put a debug and then slow the things it will correctly generate value).
If I set another field which does not having any calculation it shows correctly.
How to overcome above issue ?
Part of my model code as below.
public class Invoice
{
public Invoice() { Id = Guid.NewGuid(); Created = DateTime.Now; }
public Guid Id { get; set; }
public decimal LatestTotal { get; set; }
[NotMapped]
public decimal Total
{
get
{
return (LatestTotal = this.CalculateTotal());
}
}
}
Problematic property is LatestTotal
Action Method Looks like below
public ActionResult GetServiceAndRetailSalesDetails(Guid invoiceOrSaleId, string providerKey, DateTime checkoutDate, double checkoutTime)
{
var items = new List<CheckOutServiceAndRetailItem>();
TimeSpan timeResult = TimeSpan.FromHours(checkoutTime);
var checkOut = checkoutDate + timeResult;
var serviceDetails = Repository.GetAllPayableItems(checkOut, invoiceOrSaleId).ToList();
foreach (var s in serviceDetails)
{
var item = new CheckOutServiceAndRetailItem
{
AllocationOrInvoiceOrSaleId = s.Allocation.AllocationId,
Name = s.Allocation.Service.Name,
Price = s.LatestTotal,
//Price = s.Total,
Class = s.Allocation.Service.IsAnExtra ? "RetailOrExtraService" : "",
};
items.Add(item);
}
return Json(items, JsonRequestBehavior.AllowGet);
}
Ajax call from UI looks like below.
$.ajax({
type: "GET",
url: "/Portal/GetServiceAndRetailSalesDetails",
dataType: 'json',
contentType: "application/json; charset=UTF-8",
data: { invoiceOrSaleId: invoiceOrSaleId, providerKey: providerKey, checkoutDate: checkoutDate, checkoutTime: checkoutTime },
success: function (response) {
make = "<table id='tblPayment'>";
var totalToBepaid = 0.0;
toBePaidItems = [];
$.each(response, function (index, sr) {
if (unPaid) {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td><td></tr>";
} else {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td></tr>";
}
totalToBepaid += sr.Price;
//insert into array
toBePaidItems.push(sr.AllocationOrInvoiceOrSaleId);
});
var lateFee = parseFloat($("#hdnLateFee").val());
if (lateFee > 0) {
totalToBepaid += lateFee;
make += "<tr class='Fees'><td style='padding-right:100px'>Late Pickup Fee</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + lateFee + "</td></tr>";
}
make += "</table>";
$("#serviceAndRetailDetails").html(make);
}
});
UI Image as below (when I put a brake point and run then correct value shows)

Categories