asp button is not working for js script - c#

I have js code which gets which gets users lat long but the problem is when I call the js function in my asp.net control button it does not work and no alert is shown and the function getLocation does not work
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { x.innerHTML = "Geolocation is not supported by this browser."; }
}
function showPosition(position) {
// var latlondata = position.coords.latitude + "," +position.coords.longitude;
var latlon = position.coords.latitude;
alert(latlon)
document.getElementById('<%=abc123.ClientID%>').innerText = latlon;
}
function showError(error) {
if (error.code == 1) {
x.innerHTML = "User denied the request for Geolocation."
}
else if (err.code == 2) {
x.innerHTML = "Location information is unavailable."
}
else if (err.code == 3) {
x.innerHTML = "The request to get user location timed out."
}
else {
x.innerHTML = "An unknown error occurred."
}
}
and here is my control code
<asp:Label ID="abc123" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="getLocation()" OnClick="Button1_Click " />

The OnClick event will reload the page and therefore the JS called from the OnClientClick will never be triggered. Remove the OnClick event.
Edit:
If you need to trigger the serverside event let your JS trigger it after the alert.

Just add the following code to your button:
OnClientClick="getLocation(); return false;"

Related

EnablePageMethods in asp.net doesn't work in plesk panel

i have problem with execute page methods when i upload my website on Plesk panel .
my code in page.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
and i call java script like
function checkUserMeliCode(meliCode)
{
PageMethods.IsMeliAvailable(meliCode, onSucceeded);
}
function onSucceeded(result, userContext, methodName) {
if (methodName == "IsMeliAvailable") {
if (result == true) {
spanAv.innerHTML = "<span style='color:green'> <li class='fa fa-check' ></li> معتبر </span>";
}
else {
spanAv.innerHTML = "<span style='color:Red'> <li class='fa fa-warning' ></li> قبلا ثبت گردیده است </span>";
}
}
and i have this code in code behind
[WebMethod]
public static bool IsMeliAvailable(string Meli)
{
Admin_Req tbl_Admin = new Admin_Req();
tbl_Admin.Req_MeliCode = Meli;
DataTable result_req = tbl_Admin.Get_ReqByMeliCode();
if (result_req.Rows.Count>0)
{
return false;
}
else
{
return true;
}
}
every thing work good until i upload my web site to panel Plesk version 9.5
any solution ?
i think i have to add something to web.conf to allow plesk send and receive PageMethod
it's link of uploaded code
website Link
Webmethod call for 4th input it's kind of number, and i call pagemethod when number count equal 10 . so fill it until it's count equal 10 and look at console
the page method need to set path ... if you don't set path for page method it will get current page ...
in conclusion when you upload your website to your host . you have to set page method path .
PageMethods.set_path("pages/AdminReq.aspx");

Can Bootbox.confirm work synchronously?

In an aspx page, there is an asp:linkbutton like this:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"
OnClientClick="javascript:return confirmExit();"
EnableViewState="false"
OnClick="ExitButtonClick"></asp:LinkButton>
And this is the javascript function:
<script type="text/javascript">
function confirmExit() {
bootbox.confirm("Are you sure?", function (confirmed) {
return confirmed;
});
}
</script>
The problem is that, as far as I know, bootbox.confirm works asynchronously, and ExitButtonClick function on code behind is executed without waiting for the user confirmation.
I found a solution that works, using a hidden button:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"></asp:LinkButton>
<asp:Button runat="server" ID="btExitHidden" onclick="ExitButtonClick" style="display:none;" />
And this is the javascript part:
<script type="text/javascript">
$("#btExit").click(function (e) {
e.preventDefault();
bootbox.confirm("Are you sure?", function (confirmed) {
if (confirmed) {
$("#btExitHidden").click();
}
});
});
</script>
My question is if there is a more "beautiful" and "standard" way to work synchronously with a Bootbox.confirm, without using a hidden button.
You can make a custom sync bootbox function this way:
function ayncBootbox(message, cb = null) { // cb : function
return new Promise(resolve => {
bootbox.confirm({
message: message,
buttons: {
confirm: {
label: "Yes"
},
cancel: {
label: "No"
}
},
callback: cb ? result => cb(resolve, result) : result => resolve(result)
})
})
}
then you can call it this way by passing a custom callback if you need to do some extra stuff
var result = await ayncBootbox("message", (resolve, result) => resolve(result))
Or just
var result = await ayncBootbox("message")
PS: don't forget to make the caller function as async as well :) and you can extend this code more with reject if needed
My solution
#Html.ActionLink("Delete", "DeleteReport", new { id = item.Id }, new { #class = "btn btn-danger", onclick = String.Format("return ASE.ConfirmAction(this.href, 'Delete {0}?');", item.Name) })
var ASE = {
ConfirmAction: function (href, text) {
bootbox.confirm(text, function (result) {
if (result)
window.location = href;
});
return false;
}
}

check if website is online - problems with postback

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.

How to call both javascript function and C# function on a single button click in MVC

I want to call a javascript and a function written in Model Class using a single button click. I used the following code:
<script language="javascript" type="text/javascript">
function RunEXE() {
var txtfile = document.getElementById("txtFileName");
//var txtProgram = document.getElementById("txtProgram");
//if ((!String.IsNullOrEmpty(txtfile)) && (!String.IsNullOrWhiteSpace(txtProgram))) {
if (txtfile.value != "") {
var oShell = new ActiveXObject("WScript.Shell");
//var prog = "c:\\Pgms\\sample0.exe";
var prog = "\\\\Test-PC\\Programms\\" + txtfile.value + ".exe";
oShell.Run('"' + prog + '"', 1);
} else {
alert('The file name must be entered in file name textbox');
}
}
</script>
<input type="submit" name="button" value="Run" onclick="RunEXE()" />
The below code is Model function:
public ActionResult Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
return null;
}
But its working with Run() alone and not running RunEXE()
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { #Success = true, #MyString = "a string" });
}
$.post('#Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
In your case, you can submit your form by JQuery submit function.
I assume your code will like below:
<form id="form" action="/Run">
// your some inputs
<input type="submit" name="button" value="Run" />
</form>
And the javascript for submitting will be:
$(function() {
$('#form').submit(function() {
// to do something before the form is submitted
RunEXE();
return true; // return false to cancel form action
});
});
Cheers.

Want to get GPS coordinates in c# codebehind

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.

Categories

Resources