Why ajax call not calling the static web method? - javascript

I am calling an static web method, the method is written in an aspx.cs file having two public classes:
public class Employee
{
public string EmployeeNumber;
public string FullName;
public string LoginName;
public string EmailID;
public string Phone;
}
public partial class CustomWebMethods : LayoutsPageBase
{
[WebMethod]
public static List<Employee> GetEmployeeDetails(string employeeLoginName)
{
List<Employee> lstEmployeeDetail = new List<Employee>();
//do something
return lstEmployeeDetail;
}
}
If I keep the public class employee in the same page then ajax call is working fine.
But if I move the employee to another class library project and add reference of that project, ajax call is not working. Why?
Javascript method not able to call the web method at all.

This is because of WebMethod attribute internal works. When you mark some method with this attribute, it will be available through PageName.aspx/MethodName url.
Then, after moving this method to outer library, you moving it from the page methods too, and after that it's not available.
So, if you want to refactor your code, you have to add the WebService to your project, from that class you can call methods from other library.
You can also create a javascript proxy on your client like this:
<asp:ServiceReference InlineScript="true" Path="~/CustomersService.asmx"/>
Or use the ScriptManager for it, like this:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
After that you can use this proxy instead of ajax call.
<script type="text/javascript">
function Add()
{
var x = $get("txtX").value;
var y = $get("txtY").value;
PageMethods.Add(x, y, OnWSAdd);
}
function OnWSAdd(result)
{
$get("spanAddResult").innerHTML += result;
}
</script>
Old, but great article about Understanding ASP.NET AJAX Web Services.

Related

C# winforms webbrowser control with Javascript

I have an HTML page loaded in the webbrowser control. The HTML has a javascript function windows.print which tries to print from my browser. Please how can I pass the windows.print() function to print through Winforms C#. Or how can I pass the javascript object I want printed into the C# to be printed.
Please I am a beginner with C#, I would appreciate a detailed explanation. Thanks so much!
you can probably do something like this
namespace WindowsFormsApplication
{
// This first namespace is required for the ComVisible attribute used on the ScriptManager class.
using System.Runtime.InteropServices;
using System.Windows.Forms;
// This is your form.
public partial class Form1 : Form
{
// This nested class must be ComVisible for the JavaScript to be able to call it.
[ComVisible(true)]
public class ScriptManager
{
// Variable to store the form of type Form1.
private Form1 mForm;
// Constructor.
public ScriptManager(Form1 form)
{
// Save the form so it can be referenced later.
mForm = form;
}
// This method can be called from JavaScript.
public void MethodToCallFromScript()
{
// Call a method on the form.
mForm.DoSomething();
}
// This method can also be called from JavaScript.
public void AnotherMethod(string message)
{
MessageBox.Show(message);
}
}
// This method will be called by the other method (MethodToCallFromScript) that gets called by JavaScript.
public void DoSomething()
{
// Indicate success.
MessageBox.Show("It worked!");
}
// Constructor.
public Form1()
{
// Boilerplate code.
InitializeComponent();
// Set the WebBrowser to use an instance of the ScriptManager to handle method calls to C#.
webBrowser1.ObjectForScripting = new ScriptManager(this);
// Create the webpage.
webBrowser1.DocumentText = #"<html>
<head>
<title>Test</title>
</head>
<body>
<input type=""button"" value=""Go!"" onclick=""window.external.MethodToCallFromScript();"" />
<br />
<input type=""button"" value=""Go Again!"" onclick=""window.external.AnotherMethod('Hello');"" />
</body>
</html>";
}
}
}

switching bw Javascript and GWT function

I am working on a project using GWT and d3. i have used d3 in javascript files. Let me explain a bit more . i have a class name AstForm in GWT. in this class i have a function which i have called in my javascript file using following code.it the code works fine for me.
public native void PrepareFunctionsForJS() /*-{
$wnd.ExtractOFFNetWork = this.#org.valcri.asstsrchui.client.AstForm::ExtractOFFNetWork(*);
}-*/;
public void ExtractOFFNetWork(JsArrayMixed args)
{
Window.alert("thisCurrent row and Column is " +
args.getString(0) + " " + args.getString(1)+"OffenderNetwork?");
}
void testfunction ()
{
Window.alert("testfunction)
}
in java script i have used the following code
window.ExtractOFFNetWork(["GWT","JS"]);
my code works fine. i can call the ExtractOFFNetWork in javascript file. however the problem is in the ExtractOFFNetWork function when i call testfunction which is also the member function of the ASTFORM class the programe error saying testfunction is not a function. however when i changed testfunction as static than i can access this function within ExtractOFFNetWork. alternatievly i can also use the testfunction inside ExtractOFFNetWork by creating a separate object of ASTForm as
AstForm my =new AstForm();
my.testfunction();
however i do not want to use either static or separate ASTform object to access member function of ASTForm. i also used this.testfunction() within ExtractOFFNetWork but it also does not work. i would appreciate if any body can help to solve my problem i have spend full day without any success :)
already tried this when calling your PrepareFunctionsForJS(btw by java naming conventions method names start with lowercase letter..)
//assuming that you are calling the prepare function from inside the AstForm
public class AstForm() {
//...
PrepareFunctionsForJS(this);
}
public native void PrepareFunctionsForJS(AstForm instance) /*-{
$wnd.ExtractOFFNetWork = instance.#org.valcri.asstsrchui.client.AstForm::ExtractOFFNetWork(*);
}-*/;

ASP.net javascript call code behing method

I am creating a asp.net web application and I want to know how to call, code behind method in javascript. Following Java script shows that getting the values of multiple textboxes with same name in to array.
using code behind method, I try to pass the values of an array ,but it didn't works. when I am using alert box, it display the textbox values .
function JavaScriptFunction() {
var arr = $("input[name='multiple[]']");
$.each(arr, function (i, item) {
alert($(item).val());
});
}
When I am call code behind method before alert box method, then it won't display any message box. (Testing code behind method)
function JavaScriptFunction() {
var arr = $("input[name='multiple[]']");
$.each(arr, function (i, item) {
PageMethods.setemail("Paul Hayman");
alert($(item).val());
});
}
This is my testing code behind method. TextBox1 I used just for testing.
[WebMethod]
public void setemail(string p)
{
TextBox1.Text = p;
}
Then finally I import webService reference.
using System.Web.Services;
This is I used webforms for button
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="JavaScriptFunction()" OnClick="Button1_Click" />
WebMethod can't interact directly with the DOM. WebMethods are outside the scope of the normal page model.
In fact, WebMethod is no longer supported by MS and you shouldn't use it. Instead, if you're on .NET 4.5 you can create a Web API and call into it with AJAX (jQuery has great helper functions for this, I see you tagged it). The Web API will return the string, and then you can use JavaScript to set the text of the textbox.
Web API
public class TestController : ApiController
{
public string GetHello(string name)
{
return String.Format("Hello, {0}!", name);
}
}
Then the jQuery AJAX code:
$.ajax({
url: '/api/test/GetHello?name=Nade',
type: 'GET'
})
.success(function(output){
$('#TextBox1').val(output);
});
If you're not on .NET 4.5, upgrade! If upgrading isn't possible, then you could just set up a generic handler (.ashx) and write to the response.

GWT + SmartGWT + Javascript: external script integration

I am building a web application using GWT and SMartGWT and I need to integrate an external script for a Photo Gallery: http://slideshow.triptracker.net/.
My current attempt is:
ScriptInjector.fromUrl("http://slideshow.triptracker.net/slide.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).inject();
Afterwards, I call this method:
Code:
native static void example(String p) /*-{
$wnd.viewer = new $wnd.PhotoViewer();
$wnd.viewer.add(p)
$wnd.viewer.show(0);
}-*/;
This does not give any error, but the photogallery appears BEHIND my Entry Point Layout, so it's not possible to use it.
So, I am trying to find a workaround and I would like to refer to the main layout from Javasript, to run the script on that. Is this possible? I've tried with
foo.getElement().getId();
but it returns me something like
isc_VLayout_0_wrapper
However, Javascript doesn't like it.
Then I tried
foo.getDOM.getId();
isc_1
But the result doesn't change.
Can someone help me fix this issue?
Thank You.
I think here are two things, that are possibly wrong:
You have an onSuccess() callback you can call the jsni call from within.
//1
ScriptInjector.fromUrl("http://slideshow.triptracker.net/slide.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
//3a
}
public void onSuccess(Void result) {
example("works");
//3b
}
}).inject();
//2
example("not loaded");
You may also try to call .setWindow(ScriptInjector.TOP_WINDOW) before calling .inject()

How to handle Javascript events via WebBrowser control for WinForms

I have read WebBrowser Control from .Net — How to Inject Javascript, Is it possible to call Javascript method from C# winforms and many others. Those examples were returns function value or alert window (synchronous calls). I have to get result from event handler (async call):
<script type="text/javascript">
window.onload = function() {
var o = new M.Build(document.getElementById("ZID"));
M.Events.observe(o, o.Events.Success, function() {
// I have to get some value!!
});
M.Events.observe(o, o.Events.Fault, function() {
// I have to get some value!!
});
}
</script>
Calling C# from JavaScript
Simply put, you can expose a C# object
to the WebBrowser that the JavaScript
can call directly The WebBrowser
class exposes a property called
ObjectForScripting that can be set by
your application and becomes the
window.external object within
JavaScript. The object must have the
ComVisibleAttribute set true
C#:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class ScriptInterface
{
public void callMe()
{
… // Do something interesting
}
}
webBrowser1.ObjectForScripting = new ScriptInterface();
Javascript:
window.external.callMe();
Calling JavaScript in a WebBrowser control from C#
This is code I have. In the DocumentCompleted event ('cause I'm getting a page from online)
var wb = (WebBrowser)sender
//Lots of other stuff
object obj = wb.Document.InvokeScript("MyFunctionName");
Create a function that returns whatever value you need and invoke away.
You can also inject a script into the page
string js = "function MyFunctionName(){alert('Yea!');}";
HtmlElement el = wb.Document.CreateElement("script");
IHTMLScriptElement element2 = (IHTMLScriptElement)el.DomElement;
element2.text = js;
head.AppendChild(el);
which can then be invoked. That's what I've done.
If your webBrowser control is in a form, you can do the following:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1
{
public Form1()
{
InitializeComponent();
webBrowser1.ObjectForScripting = this;
}
public void CallMe()
{
//.... this method can be called in javascript via window.external.CallMe();
}
}

Categories