Calling Web Method in Web Service - c#

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

Related

ASP.NET C# Form Submission Problems

I have built a form with jqueryui-date picker - basically if the end date is less than or equal to start time it needs to display a message saying it must be greater than the start time before allowing the user to submit the form. Cannot see where i am going wrong.
Code Below on Submit
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text + " " + ddlTime.SelectedValue);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text + " " + ddlTime2.SelectedValue);
if (startDate >= DateTime.Now)
{
if (endDate <= startDate)
{
usrComment.Visible = true;
//usrComment.Text = "Return time needs to be greater than pickup time IF same day";
usrComment.Text = "Date =" + startDate + "Date 2 =" + endDate;
}
else
{
if (Page.IsValid)
{
string EmailServer = WebConfigurationManager.AppSettings["Email.Server"];
int ServerPort = Int32.Parse(WebConfigurationManager.AppSettings["Email.ServerPort"]);
string EmailServerUser = (WebConfigurationManager.AppSettings["Email.UserName"]);
string EmailServerPass = (WebConfigurationManager.AppSettings["Email.Password"]);
string EmailFrom = (WebConfigurationManager.AppSettings["Email.From"]);
string EmailTo = (WebConfigurationManager.AppSettings["Email.To"]);
string EmailToUser = txtEmail.Text;
string EmailSubject = "Quote Form submitted";
****.****.*****.Email m = new ****.****.Helpers.Email(EmailServer, ServerPort, EmailServerUser, EmailServerPass);
StringBuilder html = new StringBuilder();
html.AppendLine("<ul>");
html.AppendLine("<li>" + lblName.Text + ": " + txtName.Text + "</li>");
html.AppendLine("<li>" + lblEmail.Text + ": " + txtEmail.Text + "</li>");
html.AppendLine("<li>" + lblPhone.Text + ": " + txtPhone.Text + "</li>");
html.AppendLine("<li>" + lblVehicleType.Text + ": " + ddlVehicleType.SelectedValue + "</li>");
html.AppendLine("<li>" + lblPickupDate.Text + ": " + txtStartDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime.SelectedValue + "</li>");
html.AppendLine("<li>" + lblReturnDate.Text + ": " + txtEndDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime2.SelectedValue + "</li>");
html.AppendLine("</ul>");
m.SendHTMLEmail(EmailFrom, EmailTo, EmailSubject, html.ToString());
//Response.Redirect("/contact-us/quote-form-submitted.aspx");
}
usrComment.Text = "SUBMIT IT NOW!!!!!";
}
}
}
jQuery for the date picker
$(function () {
function getDiff() {
var from = $(".start").val();
var till = $(".fin").val();
var c = from.split("/");
beg = new Date(c[2], c[1] - 1, c[0]);
var d = till.split("/");
en = new Date(d[2], d[1] - 1, d[0]);
var rest = (en - beg) / 86400000;
var txt = rest == 0 ? "" : rest + " days"
$("#res").text(txt);
}
$(".start").datepicker({
changeMonth: false,
changeYear: false,
showAnim: "fadeIn",
gotoCurrent: true,
minDate: 0, //change this to +3 to start 3 days from now
dateFormat: "dd/mm/yy",
onSelect: function (dateText, inst) {
$(".fin").val(dateText);
$(".fin").datepicker("option", "minDate", dateText);
getDiff();
}
});
$(".fin").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
showAnim: "fadeIn",
onSelect: getDiff
});
//Disabling Copy, Paste, Cut
$('.start').bind('paste', function (e) {
e.preventDefault();
//alert("You cannot paste text into this textbox!");
window.alert = function () { };
});
$('.fin').bind('paste', function (e) {
e.preventDefault();
//alert("You cannot paste text into this textbox!");
window.alert = function () { };
});
});
So if you have a pickup date of 17/09/2013 and pickup time as 08:00 and the same for return date and time it should alert you with the message and if the return date is greater than or equal to start time the return pickup time needs to be greater than 08:00 if that makes sense?
It would be nice to have a useful, constructive comment. It doesn't matter if this is the "right way" to do it. I believe this is what you're trying to do. I've just added an else to the initial if statement to inform the user to choose a Start date later than now and altered the text of the other else statement to inform the user to pick a return date later than the start date.
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text + " " + ddlTime.SelectedValue);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text + " " + ddlTime2.SelectedValue);
if (startDate >= DateTime.Now)
{
if (endDate <= startDate)
{
usrComment.Visible = true;
usrComment.Text = "Please enter a Return date later than " + startDate;
}
else
{
if (Page.IsValid)
{
string EmailServer = WebConfigurationManager.AppSettings["Email.Server"];
int ServerPort = Int32.Parse(WebConfigurationManager.AppSettings["Email.ServerPort"]);
string EmailServerUser = (WebConfigurationManager.AppSettings["Email.UserName"]);
string EmailServerPass = (WebConfigurationManager.AppSettings["Email.Password"]);
string EmailFrom = (WebConfigurationManager.AppSettings["Email.From"]);
string EmailTo = (WebConfigurationManager.AppSettings["Email.To"]);
string EmailToUser = txtEmail.Text;
string EmailSubject = "Quote Form submitted";
****.****.*****.Email m = new ****.****.Helpers.Email(EmailServer, ServerPort, EmailServerUser, EmailServerPass);
StringBuilder html = new StringBuilder();
html.AppendLine("<ul>");
html.AppendLine("<li>" + lblName.Text + ": " + txtName.Text + "</li>");
html.AppendLine("<li>" + lblEmail.Text + ": " + txtEmail.Text + "</li>");
html.AppendLine("<li>" + lblPhone.Text + ": " + txtPhone.Text + "</li>");
html.AppendLine("<li>" + lblVehicleType.Text + ": " + ddlVehicleType.SelectedValue + "</li>");
html.AppendLine("<li>" + lblPickupDate.Text + ": " + txtStartDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime.SelectedValue + "</li>");
html.AppendLine("<li>" + lblReturnDate.Text + ": " + txtEndDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime2.SelectedValue + "</li>");
html.AppendLine("</ul>");
m.SendHTMLEmail(EmailFrom, EmailTo, EmailSubject, html.ToString());
//Response.Redirect("/contact-us/quote-form-submitted.aspx");
}
usrComment.Text = "SUBMIT IT NOW!!!!!";
}
}
else
{
usrComment.Visible = true;
usrComment.Text = "Please enter a Start date later than " + DateTime.Now;
}
}
I suggest you not to use any kind of custom function.
JquerUI-date picker have inbuilt functionality for comparing end date with start date.
Please try this
http://jqueryui.com/datepicker/#date-range

Geting out put from Script Html agility pack

i am having problem that this following script generates Email address when page is loaded and i want to parse that email how can i do that?
tr>
<td align='right' class='generalinfo_left' >Email Address:</td>
<td class='generalinfo_right'><script type="text/javascript">
//<![CDATA[
var o3752aaa9bb29d904adeb88838117fd7c = String.fromCharCode(109);var f03de7e643c296e211edddbc3197b33f6 = String.fromCharCode(97);var k7c3bf82468602c0f8dff4950e4b6ff1e = String.fromCharCode(105);var b3eaa633e44451be8df1fa47d75149934 = 'l';var ma2fa16c3a3f532b780aaf0fa5a5b75c6 = 't';var re0c13fc69c03925782867a0540f8c084 = 'o';var j335f1365672123d1fcaf9a83b76f1b7b = String.fromCharCode(58);var f32820e1c54cbc3fa0d418cd1c195eaec = String.fromCharCode(105);var y8c24ea00a7a1edf1c01f794d487697e3 = String.fromCharCode(110);var bcc0ad4f628e703f9ff6e25b87b77ec34 = 'f';var c985c961c7ee85fe6a25d5a66fb421745 = String.fromCharCode(111);var z5ab4e3bdc353d621cea5babcc5dca417 = String.fromCharCode(64);var s4e087167cd0bac466344e72016511172 = String.fromCharCode(97);var re26f6ae180723793af62bc36d5ab2530 = String.fromCharCode(108);var ye1b53d01de118079a38de5e951586731 = 'c';var g9fc5710c9266ce08afbe4da24702dfdd = String.fromCharCode(105);var k5cd5ea1bac40fdbb8b133b7e356809c6 = String.fromCharCode(118);var fcd6e4771e956e270c6897d24ca51c256 = String.fromCharCode(97);var y9d7854a5921fa2be88c8cd72c7e2884e = String.fromCharCode(114);var xa58bea1ecad6fe7d2c736aab1df2df44 = '.';var e4569f6c98804675f7117a84abb0b8d5c = 'c';var o4d2081e2344020922dcb924690c9972e = 'o';var af150185e5eef8ecd8dc1b0a4977c7d55 = String.fromCharCode(109);document.write("<a href='" + o3752aaa9bb29d904adeb88838117fd7c + f03de7e643c296e211edddbc3197b33f6 + k7c3bf82468602c0f8dff4950e4b6ff1e + b3eaa633e44451be8df1fa47d75149934 + ma2fa16c3a3f532b780aaf0fa5a5b75c6 + re0c13fc69c03925782867a0540f8c084 + j335f1365672123d1fcaf9a83b76f1b7b + f32820e1c54cbc3fa0d418cd1c195eaec + y8c24ea00a7a1edf1c01f794d487697e3 + bcc0ad4f628e703f9ff6e25b87b77ec34 + c985c961c7ee85fe6a25d5a66fb421745 + z5ab4e3bdc353d621cea5babcc5dca417 + s4e087167cd0bac466344e72016511172 + re26f6ae180723793af62bc36d5ab2530 + ye1b53d01de118079a38de5e951586731 + g9fc5710c9266ce08afbe4da24702dfdd + k5cd5ea1bac40fdbb8b133b7e356809c6 + fcd6e4771e956e270c6897d24ca51c256 + y9d7854a5921fa2be88c8cd72c7e2884e + xa58bea1ecad6fe7d2c736aab1df2df44 + e4569f6c98804675f7117a84abb0b8d5c + o4d2081e2344020922dcb924690c9972e + af150185e5eef8ecd8dc1b0a4977c7d55 + "'>" + f32820e1c54cbc3fa0d418cd1c195eaec + y8c24ea00a7a1edf1c01f794d487697e3 + bcc0ad4f628e703f9ff6e25b87b77ec34 + c985c961c7ee85fe6a25d5a66fb421745 + z5ab4e3bdc353d621cea5babcc5dca417 + s4e087167cd0bac466344e72016511172 + re26f6ae180723793af62bc36d5ab2530 + ye1b53d01de118079a38de5e951586731 + g9fc5710c9266ce08afbe4da24702dfdd + k5cd5ea1bac40fdbb8b133b7e356809c6 + fcd6e4771e956e270c6897d24ca51c256 + y9d7854a5921fa2be88c8cd72c7e2884e + xa58bea1ecad6fe7d2c736aab1df2df44 + e4569f6c98804675f7117a84abb0b8d5c + o4d2081e2344020922dcb924690c9972e + af150185e5eef8ecd8dc1b0a4977c7d55 + "</a>")
//]]>;
</script></td>
out put is like this
<td class="generalinfo_right">
<script type="text/javascript">
same above script plus following Line
</script>someID#email.com</td>
I wrote my own custom parser that will read the script and parse Email from it.here goes the code
If this code can be optimized or can be written more neatly please let me know
private string ReadEmail(string EmailScript)
{
string EncriptedEmail = "";
string dataPart = "";
dataPart = EmailScript.Substring(0, EmailScript.IndexOf("document.write")).Replace("//<![CDATA[\r", "").Replace("\"", "").Replace("\r\n","");
EncriptedEmail = EmailScript.Replace("\"","");
EncriptedEmail = EncriptedEmail.Substring(EncriptedEmail.IndexOf("'> + "), EncriptedEmail.IndexOf(" + </a>") - EncriptedEmail.IndexOf("'> +")).Replace("'> +", "").Trim();
string[] requiredVariables = EncriptedEmail.Split('+');
List<string> ExtractedDataFromRaw = new List<string>();
string email = "";
foreach (string variable in requiredVariables)
{
string temp = dataPart.Substring(dataPart.IndexOf(variable),dataPart.Length-dataPart.IndexOf(variable)).Replace(" ","");
string tempValueofVariable = temp.Substring(0, temp.IndexOf(";"));
tempValueofVariable = tempValueofVariable.Substring(tempValueofVariable.IndexOf("="), tempValueofVariable.Length - temp.IndexOf("=")).Replace("=","");
if (tempValueofVariable.Contains("String.fromCharCode"))
{
tempValueofVariable = GetCharacterFromASCII(tempValueofVariable.Replace("String.fromCharCode(", "").Replace(")", ""));
}
ExtractedDataFromRaw.Add(tempValueofVariable.Replace("'",""));
email += tempValueofVariable.Replace("'", "");
}
return email;
}
private string GetCharacterFromASCII(string value)
{
int result = 0;
int.TryParse(value, out result);
return char.ConvertFromUtf32(result);
}
That code is building the email address one character at a time from character codepoints and then assembling it later. I suppose this is an attempt to prevent email spam. Depending on what you need to do, it might be easiest to just pull the email address from the link using jQuery or something. $('a[href^=mailto]').attr('href').substring(7) or something ought to do it.

JavaScript Google map marker bug

I'm currently working on an ASP.NET project where I'm using the Google Maps API to show a marker for every company that's registrated in the database.
Everything works just fine, but when I click on a marker the tooltip/dialogbox for the last company in my company list always shows up and not the actualy company mark that's been clicked on.
I can't really get my head around why it is always the last marker that shows up. Here's my updated code:
JavaScript.Text = #"<script type='text/javascript'>
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById('map'));
map.setCenter(new GLatLng(56.4, 10.57983), 9);
map.enableScrollWheelZoom();
}
}
</script> ";
foreach (MemberProfile m in relatedMembers)
{
XmlDocument doc = new XmlDocument();
string address = m.Address;
string zip = m.Zip;
string city = m.City;
string navn = m.Name;
string tlf = m.Phone;
doc.Load("http://maps.googleapis.com/maps/api/geocode/xml?address=" + zip + "+" + city + "+" + address + "+DK&sensor=true&key=ABQIAAAAEaY4JLb9fZFGMlDKuMUlWBRSvyGIkBO7X03pzlT7Z30EPXHR8BS0rXL_ShFm2gc79lZTw2Zak88wng");
XmlNode latNode = doc.SelectSingleNode("GeocodeResponse/result/geometry/location/lat/text()");
XmlNode lonNode = doc.SelectSingleNode("GeocodeResponse/result/geometry/location/lng/text()");
if (latNode != null && lonNode != null)
{
JSAddMarkers.Text += #"<script type='text/javascript'>
var marker = new GMarker(new GLatLng(" + latNode.Value + "," + lonNode.Value + ")); "
+ "var html = '<b>" + navn + "</b><br />" + address + "<br /> " + zip + " " + city + "<br />" + tlf + "'; " + "GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); });"
+ "map.addOverlay(marker);"
+ "</script>";
}
If any of you out there can spot the reason why, I would be happy to hear from you! Any help/hint is appreciated :-)
All the best,
Bo
try this
var point =new GLatLng(" + latNode.Value + "," + lonNode.Value + ");
var marker = createMarker(point, address,zip,city,navn);
map.addOverlay(marker);
function createMarker(point, address, zip,city, navn) {
var marker = new GMarker(point, customIcons[type]);
var html = "Address:<b style='padding-left:6px'>" + address+ "</b><br/>zip:<b style='padding-left:6px'>"+ zip+ "</b><br/>city:<b style='padding-left:6px'>"+ city+ "</b>";
GEvent.addListener(marker, 'mouseover', function() {
marker.openInfoWindowHtml(html);
});
GEvent.addListener(marker, "mouseout", function() {
marker.closeInfoWindow();
});
return marker;
}

jQuery calls asmx web method multiple times

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.

Browser detection

I need to separate IE and FF browsers from others
it's a pseudo-code :
If (CurrentBrowser == IE(6+) or FF(2+) )
{
...
}
else
{
...
}
in protected void Page_Load() event (think so)
if ((Request.Browser.Type == "IE") || (Request.Browser.Type == "FF"))
{
WebMsgBox.Show("1111");
}
no effects :-/ what is IE and FF types?
if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
...
}
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
if (Request.Browser.MajorVersion < 7)
{
DoSomething();
}
...
}
else { }
Here's a way you can request info about the browser being used, you can use this to do your if statement
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n";
MSDN Article
Try the below code
HttpRequest req = System.Web.HttpContext.Current.Request
string browserName = req.Browser.Browser;
private void BindDataBInfo()
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Literal1.Text = "<table border=\"1\" cellspacing=\"3\" cellpadding=\"2\">";
foreach (string key in browser.Capabilities.Keys)
{
Literal1.Text += "<tr><td>" + key + "</td><td>" + browser[key] + "</tr>";
}
Literal1.Text += "</table>";
browser = null;
}
I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.
Or use these libs to determine the browser type if you really must.
Also see Browser & version in prototype library?
For browser compatibility you can use this code. This method returns browser name and version :
private string GetBrowserNameWithVersion
{
var userAgent = Request.UserAgent;
var browserWithVersion = "";
if (userAgent.IndexOf("Edge") > -1)
{
//Edge
browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Chrome") > -1)
{
//Chrome
browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Safari") > -1)
{
//Safari
browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Firefox") > -1)
{
//Firefox
browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("rv") > -1)
{
//IE11
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("MSIE") > -1)
{
//IE6-10
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Other") > -1)
{
//Other
browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
}
return browserWithVersion;
}
I tried and found the solution for the same
public static string GetBrowserDetails()
{
string BrowserDetails = HttpContext.Current.Request.Browser.Browser + " - " + HttpContext.Current.Request.Browser.Version + "; Operating System : " + HttpContext.Current.Request.Browser.Platform;
return BrowserDetails;
}
OUTPUT :
Chrome - 88.0; Operating System : WinNT
use from
Request.Browser
this link will help you :
Detect the browser using ASP.NET and C#

Categories