ASP.NET AJAX - ScriptManagerProxy and handling html button clicks - javascript

I am trying to figure out how to accomplish the following:
Handle client-side click event of button - prevent postback if result of javascript call is false (e.g. onclick="js:return IsThisAllowed()")
Javascript method will return true or false, depending on result of call to generated web service method using ScriptManagerProxy
The code below is simplified down to the main components that I am referring to in this question. I can alert() the return value no problem, but the part I'm having trouble with is how I can return the result of the web service method call back to the button onclick handler? Since the function Finish() is called in a separate thread upon success of what I assume is the XmlHttp.send() call, how can I send the value of the response as the return value of the javascript method? Am I going about this all wrong?
I've used similar code many times before to update the DOM with the return values, such as within a <div>, but never had to worry about capturing the return value and using it within my script.
What I have so far:
.NET web service method (VB.NET):
<WebMethod()> _
<ScriptMethod()> _
Public Function IsAllowed() As Boolean
Return True
End Function
.NET code for the page to generate AJAX web service methods, and html button
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MyWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
<asp:Button ID="_btn" runat="server" OnClientClick="js:return IsAllowed();" />
Javascript
<script type="text/javascript">
function IsAllowed(orderid) {
if (!processing) {
processing = true;
var ws = new MyWebService();
ws.IsAllowed(Finish, Error)
// return TRUE if call to IsAllowed returns true!!!
return false;
}
}
function Finish(result) {
alert(result)
}
function Error() {
}
</script>

You can't do this: the call to the web service is an asynchronous request to the server that immediately returns control to the client - and your javascript is (almost) always going to finish executing before the request completes (most likely before the request is even delivered).
Since you don't know when you'll receive the response from the call to ws.IsAllowed, you need to handle it in your callbacks (Finish and Error).
(This is true whatever AJAX mechanism you're using.)
I'm not familiar enough with ScriptManager-based AJAX to tell you exactly how to do this, but the general idea is that I'd turn it around: instead of canceling an ASP.NET button's click event, I'd only trigger the ASP.NET button if the AJAX call returned true.
Using jQuery, I'd do it by making the AJAX call from a vanilla HTML button (not an ASP.NET web control). In the success handler (the equivalent of Finish), I'd trigger my ASP.NET button (which I'd probably hide) when the return value is true.

Have you considered using jQuery?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "~/WebServices/IsAllowed.asmx/{Method Name}",
data: ('{ whatever data is needed for decision making json serialized }'),
success: function (msg) {
alert(msg);
},
error: function (request, status, error) {
alert(err.Message);
alert(err.StackTrace);
}
});

Related

Jquery AJAX button call in Umbraco BackOffice

Hi I just created a simple new option for umbraco backoffice, it is a simple html page which displays a button to click.
Simple form
This button should send an ajax call to an UmbracoApi, but the request never reaches the webapi. Below the Api Code:
API Code
The Ajax call is a simple Jquery Ajax call in the event click of the html button.
I'll appreciate any help you can provide me, in order to complete this ajax call.
I think yor problem is the way you are calling it:
not sure if url casing not same as Controller and action will cause routing failure or not, but might as well make then the same
you action is binding a primitive type, from my understanding of webapi - primitive type will check at querystring otherwise specifically tell it to look at body
more info about this, checkout https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
so base on above two statement, try change your call to:
$("#btnGetData").click(function() {
$.ajax("http://localhost:44302/Umbraco/Api/StripeBackOfficApi/GenerateLockBoxile?date=" + $('#txtDate').val(), {
type: "GET"
}, cache: false, success: function(data, status, headers, config) {
if (data) {
alert("Done!");
}
}, error: function(jqXHR, timeout, message) {
console.log("Error: " + message);
}
});
});

Call WebMethod in C# codebehind without using a server form in ASPX page

Due to issues with styling, and needing multiple forms on one single web page, I currently have a form that is outside of the normal form with runat=server.
Is it possible for me to still call a WebMethod in the C# codebehind of this web page using ajax? I want to submit the information from this form to the same connection string that I am using earlier in the page, in a different form.
Here is my current code:
$().ready(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
function createJob() {
var txtTestValue = document.getElementById('jobTitle').value;
$.ajax({
// POST signals a data request
type: "POST",
// This directs which function in the c# code behind to use
url: "Account/help.aspx/CreateJob",
// The paramater pageIndex, page number we need to load, to pass to GetCustomers(int pageIndex)
data: txtTestValue,
// Type of data we are sending to the server (i.e. the pageIndex paramater)
contentType: "application/json; charset=utf-8",
// Type of data we expect back from the server (to fill into the html ultimately)
dataType: "text",
// If all goes smoothly to here, run the function that fills our html table
success: OnSuccess,
// On failure, error alert user (aka me so that I know something isn't working)
failure: function (response) {
alert("failure");
},
error: function (response) {
alert("error");
}
});
});
And my WebMethod in the codebehind:
[WebMethod]
public string CreateJob()
{
//rest of my database code here
}
Sorry for the confusion but it's doing everything right up until the ajax code, and then seems to ignore it (and returns that the ajax failed with an error). My code is not reaching the WebMethod and any breakpoints I set in Visual Studio are not triggered in the page header. Thanks in advance for your help!
You need to declare the method as static.
[WebMethod]
public static string CreateJob()
^^^^^
{
//rest of my database code here
}
Another issue is if input[type=submit] is ASP.Net Button control, it will post back to server. You cannot use ASP.Net Server control to make jQuery Ajax call - $.ajax.
// This code won't work if `input[type=submit]` is a server button control
$(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
you need to use regular html input or button control with type=button instead of type=submit.
The webmethod should be static.
[WebMethod]
public static string CreateJob()
{
//rest of my database code here
}

Calling a static method from cshtml file

I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background
I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.
You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?

How to pass a javascript variable to server side method

I am facing issue like I am unable to pass the javascript variable to server side I am aware that it is not achieveable in this scenario so I tried like setting the value to the asp hidden field using jQuery and getting the value of the label in server side but unfortunately I am getting empty value for the hidden field. Help me on how to fix this
CODE
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID){
<%=RenderMethod(DataID) %> // How to pass javascript variable to server side
}
Hidden Field Approach:
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID){
$("#<%=hdnDataVal.ClientID %>").val(DataID);
alert($("#<%=hdnDataVal.ClientID %>").val(DataID)); // Here using javascript I can able to set the value and when I alert the value it is displayed
<%=RenderMethod(hdnDataVal.Value) %> // here the hiddenfield value is empty
}
<asp:HiddenField runat="server" ID="hdnDataVal" />
First of all... you should not mix server code and client code the way you're doing it.
It's a poor way to design your code. Try always to separate client and server code. They execute on different moments, places and under different circumstances... having them together will eventually draw you to difficult to debug errors.
I bet that the problem you're experiencing here is due to this way of coding.
You say on your code snippet that
<%=RenderMethod(hdnDataVal.Value) %> // here the hiddenfield value is empty
When your page is loading and server code is executed the code inside $(document).ready() is not fired yet, as it fires when your whole page finish loading. So, your RenderMethod is firing before you put any value inside the variable.
try using $.ajax();
var url = 'my-url.aspx';
$.ajax({
url: url,
type: 'POST',
data: {'variable_name': my_variable },
success: function(html)
{
alert('ok');
},
});
and receiver on the server-side:
string my_variable = Request.Form['variable_name'];
You can use a Page Method to make a server side call from client side. It's propably the easiest way to accomplish what you want.
First of all you need to include the Script Manager in your aspx page with Page Methods enabled:
<asp:ScriptManager ID="scrmgr" EnablePageMethods="true" runat="server" />
Now you can invoke the server side method and pass it the client side data you want, with sth like this:
<script type="text/javascript">
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID) {
PageMethods.RenderMethod(DataID, OnSuccess, OnError);
}
function OnSuccess(result) {
alert(result);
}
function OnError() {
alert('Some error has ocurred!');
}
</script>
OnSuccess function is invoked in case the server-side method has been succesfully called. Otherwise OnError function is invoked.
This is how the Page Method should be declared inside the .aspx.cs file:
[System.Web.Services.WebMethod]
public static string RenderMethod(string dataID)
{
return "Got here!";
}
If you place a breakpoint inside RenderMethod, then you can verify that client side data (i.e. value "4325") is correctly passed to it.

WCF Service methods + Synchronous calls from javascript

I have written a WCF service and am trying to call the service methods in a script in my ASPX page.
Eg:
<script language="javascript" type="text/javascript">
<!--
function Test() {
**// The following call is an Async call.
tempuri.org.IService.GetData(1,OnRequestComplete, OnError, "");**
}
function OnRequestComplete(result, state) {
var textBox = $get("txtInput");
textBox.value = result;
}
function OnError(result) {
var textBox = $get("txtInput");
textBox.value = result;
}
//-->
</script>
What I want is to be able to call the service method "synchronously"
eg: var result = tempuri.org.IService.GetData(1);
Is this possible?
I believe there's no ability to do synchronous calls in Javascript - the AJAX libraries will always return while waiting for a remote response.
Can you explain why you want to do this?
Edit:
In answer, you should use this method:
In the onclick event handler for your form submit button: Make the webservice validation call, and immediately return false (so the form does not submit). It would be a good idea to display to the user a 'Validating' type message, so they know what is happening here.
If you get a valid response, then use document.form.submit(); to submit the form to the server.
If you get an invalid response, or a server error, then display to the user a message to that effect.
If you use regular AJAX you can make your call synchronous.
See: http://www.w3schools.com/Ajax/ajax_xmlhttprequest_send.asp
and scroll down to the part "Asynchronous - True or False?"
Here I use AJAX but sometimes it hangs
www.DomainGuarder.com

Categories

Resources