I'm having a bit of a problem with GPS coordinates. I'm able to get coordinates in asp.net / javascript using the geolocation, but need these to be available to a method in the c# codebehind. Unfortunately, for some reason the retrieved coordinates aren't, even if I put them into labels (they never end up there for some reason).
So, what I'm thinking now is to try and get the coordinates (just need the latitude and longitude) directly into c# somehow, even if I have to run some javascript through c# (unsure how you do that).
Does anyone have any ideas? I've posted the javascript below:
<button id="btnLocate" runat="server" onclick="GetLocation()" style="width: 15%">Loc</button>
<script type="text/javascript">
function GetLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(ShowPosition, ShowError, { maximumAge: 5000, timeout: 10000 });
}
else { alert("Geolocation is not supported by this browser."); }
}
function ShowPosition(position)
{
var latdata = position.coords.latitude;
var londata = position.coords.longitude;
document.getElementById("lblLat").value = latdata;
document.getElementById("lblLon").value = londata;
}
function ShowError(error)
{
if (error.code == 1)
{
alert("User denied the request for Geolocation.");
}
else if (error.code == 2)
{
alert("Location information is unavailable.");
}
else if (error.code == 3)
{
alert("The request to get user location timed out.");
}
else
{
alert("An unknown error occurred.");
}
}
</script>
I guess you want to use the coordinates in an codebehind method?
Why not just run the when you open the page, and then when you click your button, you retrieve data fra labels/textboxes?
<script type="text/javascript" id="getCord">
if(typeof navigator.geolocation === 'undefined')
{
alert("Geolocation services are not supported by your web browser");
}
else
{
navigator.geolocation.getCurrentPosition(handleLocation, handleError);
}
function handleLocation(position)
{
var lat = position.coords.latitude;
document.getElementById('<%= latTextBox.ClientID %>').value = lat;
var lon = position.coords.longitude;
document.getElementById('<%= lonTextBox.ClientID %>').value = lon;
}
function handleError(error)
{
switch (error.code)
{
case error.TIMEOUT:
alert('Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert('Position unavailable');
break;
case error.PERMISSION_DENIED:
alert('Permission denied');
break;
case error.UNKNOWN_ERROR:
alert('Unknown error');
break;
}
}
This will run without pressing an button, and your textboxes with ID latTextBox on lonTextBox will get coordinates which you can use.
Related
I have below code in my web application and have fetched data using ajax call and loaded my cshtml page, but after loading certain time my web page throwing aw!snap error in google chrome.
function Getdata() {
try {
$http.post(RootURL + '`mycontroller/GetDetails').then(function (response) {
//Reload Error page
if (response.data.iserror) {
// load error
}
else {
if (response.data != undefined) {
$scope.dataList= [];
$scope.dataList= response.data.result;
}
}
}).catch(function () {
onComplete();
});
}
catch (e) {
// UI catch e
}
}
we see web suggestions to clear objects after assigning into UI controls. Can anyone help me out in this?
How to clear objects in js after assignment?
I'm using PayPal express checkout (checkout.js V4.0.0) with asp.net mvc to allow a user to pay for data transactions. What I need to do when the express checkout button is clicked is perform some checks on the database and confirm that PayPal can proceed (this is also time related, as the database could be in a locked processing state).
I've setup the Advanced Server Integration and I then call the create-payment controller from the payment section in paypal.Button.render, but this expects a json object with a PaymentID element to be returned. At what point am I able to perform these checks on server side and abort from the paypal process if PayPal can't continue? If a check fails, the server side also needs to return an appropriate error page or message to be displayed.
This is the paypal button code:
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
paypal.Button.render({
env: 'sandbox',
payment: function (resolve, reject) {
var CREATE_PAYMENT_URL = '#Url.Action("PayTransactions","Pending")';
paypal.request.post(CREATE_PAYMENT_URL)
.then(function (data) { resolve(data.paymentID); })
.catch(function (err) { reject(err); });
},
onAuthorize: function(data) {
var EXECUTE_PAYMENT_URL = 'https://my-store.com/paypal/execute-payment';
paypal.request.post(EXECUTE_PAYMENT_URL,
{
paymentID: data.paymentID,
payerID: data.payerID
})
.then(function(data) { /* Go to a success page */ })
.catch(function (err) { /* Go to an error page */ });
},
onCancel: function (data, actions) {
return actions.redirect();
},
onError: function (err) {
// Show an error page here, when an error occurs
}
}, '#paypal-button');
</script>
which at the payment section calls this:
public async Task<string> PayTransactions()
{
// check if payment is still necessary or end of month is running
var condition = await CheckDatabaseIsUsable();
switch (condition)
{
case 1:
ModelState.AddModelError("error", "some error message");
return RedirectToAction("Index", "Pending");
case 2:
ModelState.AddModelError("error", "some other error");
return RedirectToAction("Index", "Pending");
}
var paypalPayment = FormPayPalPaymentObject();
return JsonConvert.SerializeObject(new { paymentID = paypalPayment.PaymentId });
}
The problem is that I am now mixing the ActionResult and json string return types.
You can return json also for the redirection responses and control with javascript when it is a redirection or and ok response.
Server side:
return JsonConvert.SerializeObject(new { redirect= Url.Action("Index", "Pending") });
Javascript:
paypal.request.post(CREATE_PAYMENT_URL)
.then(function (data) {
if(data.redirect)
{
//cancel the flow and redirect if needed
window.location.href = data.redirect;
}else{
resolve(data.paymentID);
}
})
.catch(function (err) { reject(err); });
},
Using an IActionResult object as the return value for the PayTransactions is preferable
public async Task<IActionResult> PayTransactions()
{
...
return Json(new { paymentID = paypalPayment.PaymentId });
}
Also consider that the modelstate errors you are adding are useless because of the redirection.
You can call reject(error) to cancel the payment.
I've got a webpage that people in my company are filling in using mobile handsets. Only problem is, if they move out of a signal area, then when they try and update their work the page will go to a "page not found" and they'll lose the work they've filled in.
I'm trying to remedy this and, at the moment, have this solution:
protected void Button1_Click(object sender, EventArgs e)
{
Session["Online"] = 0;
CheckConnect();
if ((int)Session["Online"] == 1) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently online')", true); }
if ((int)Session["Online"] == 0) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently offline')", true); }
}
protected void CheckConnect()
{
System.Uri Url = new System.Uri("http://www.mypage.com/pixel.jpg?" + DateTime.Now);
System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);
try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
Session["Online"] = 1;
}
catch
{
WebReq = null;
Session["Online"] = 0;
}
}
Now, this will check if the pixel file at www.mypage.com exists (no, that's not actually my page, I've substituted it for this example) and, if so, it returns a 0, if not a 1. Which is fine and dandy.
However, pressing the button causes the page to be reloaded. Then, if it's offline, it does the usual "page not found" business. My button code is here:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Basically, I want it to not reload the page if we're offline (or indeed if we are online, as the code that does the updating handles that part anyway).
EDIT - alright, different approach now. Doing this entirely through javascript using the following:
<asp:Button ID="Button1" runat="server" OnClientClick="ifServerOnline()" Text="Button" />
<script type="text/javascript">
function ifServerOnline(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.mypage.com/pixel.jpg?" + Date.now;
}
ifServerOnline(function ()
{
return confirm('Online');
},
function ()
{
return confirm('Offline');
});
</script>
Unfortunately still causing a page refresh.
In your page's javascript assign form onsubmit event handler, where you cancel default submit. Also, in this event handler, issue an ajax request to the server with a very brief response. In onsuccess event handler of this ajax request - resubmit the form, in onerror handler - tell the user that they lost connection to server.
You can't do postback to the server when you offline.
No way to do it..
But maybe you can do that's with javascript.. try this way.
Managed it with this...
<asp:Button ID="btnRouteC" runat="server" OnClientClick="return ifServerOnlineA(ifServerOnlineA1, ifServerOfflineA1);" Text="Route" Width="45%" />
<script type="text/javascript">
function ifServerOnlineA(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.myserver.com/pixel.jpg?" + Date.now;
return false;
}
function ifServerOnlineA1()
{
document.getElementById('btnRoute').click();
return false;
}
function ifServerOfflineA1()
{
alert("There is no connection at the moment. Please try again later.");
return false;
}
</script>
As Itiel said, it won't work through the codebehind but will through the Javascript.
i want to save a input (type = file) image to database (asp.net & mssql),
in this case i use web service, so i can't use runat= server, or i can't use server side controls.
in client side, user chose a picture, and i must save it binary to database.
var exts = ['jpg', 'jpeg', 'png', 'gif'];
var file = $(this).val();
if (file) {
var get_ext = file.split('.');
get_ext = get_ext.reverse();
if ($.inArray(get_ext[0].toLowerCase(), exts) > -1) {
if ((Math.round((this.files[0].size) / 1024)) > 35) {
alert("PLEASE REDUCE FILE SIZE");
} else {
//everything is ok
}
} else {
alert("PLEASE CORRECT FORMAT");
}
} else {
alert("PLEASE DEFINE FILE");
}
i can check file selected, type and size and know need to upload.
what can i do?
is it possible to support, ie? if yes which version?
thank you
You have to upload the image in a form using the next tag:
<form id='fileUploadForm' enctype="multipart/form-data" method="post" action="yourAction">
<input type="hidden" value="your max value in bytes" name="MAX_FILE_SIZE">
<input type="file" name="userImage">
</form>
It will be submitted for any browser.
But if you want to submit the form using ajax, you should use a plugin. I used recently this one: http://malsup.github.io/jquery.form.js. It is very simply to use.
There is another issue: files[0] will return undefined if using IE.
I use this so that IE also works:
var file = $('input[type=file]')
file.bind('change', function(e) {
e.preventDefault();
if (typeof this.files === "undefined") fileOk = file;
else fileOk = this.files[0];
....
Then, and after validation on client side, you can use this method from jquery.form plugin:
$('#fileUploadForm').ajaxSubmit(){
beforeSend: function() {},
uploadProgress: function(event, position, total, percentComplete) {},
success: function() {},
complete: function(xhr) {}
}
And the file will be submitted.
I have a simple ajax page that adds 2 numbers.
When I run in IE, the async callback works.
When I run in Firefox it doesn't work.
I get the correct return value in Firebug but lblSum remains blank in Firefox.
It has something to do with the return false at the end of the btnAdd click handler.
There is a server-side handler in case Javascript is disabled, so in the Javascript I add a return false.
<script type="text/javascript">
var pageWebForm1 = {
txt1: document.getElementById('TextBox1'),
txt2: document.getElementById('TextBox2'),
lblSum: document.getElementById('LblSum'),
btnAdd: document.getElementById('BtnAdd'),
init: function() {
this.btnAdd.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
xhrCallback(xhr.responseText);
}
}
xhr.open("POST", "Handler.ashx", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("x=" + pageWebForm1.txt1.value + "&" + "y=" + pageWebForm1.txt2.value);
return false;
}
}
}
pageWebForm1.init();
function xhrCallback(retval) {
pageWebForm1.lblSum.innerText = retval;
}
</script>
It has nothing to do with the return false statement. Your problem is innerText is IE only. Another stackoverflow post on a cross-browser solution.