I need to call the service and retrieve the resulted data in call back function from it but I am getting js error:
Uncaught ReferenceError: InvoiceHTMLService is not defined.
Please help - below are my pages and class
My Aspx page
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="InvoiceHTML.aspx.vb" Inherits="WebApplication2.InvoiceHTML" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Web Service call from client-side JavaScript</title>
<script type="text/javascript">
function SendRequest() {
debugger;
InvoiceHTMLService.GetBillInvoiceHtmlData();
}
function OnComplete(arg) {
alert(arg);
}
function OnTimeOut(arg) {
alert("timeOut has occured");
}
function OnError(arg) {
alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service/InvoiceHTMLService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="text" value="" id="MyTextBox" />
<input type="button" value="Send Request to the Web Service"
id="RequestButton" onclick="return SendRequest()" />
</div>
</form>
</body>
</html>
my asmx page
Imports System.Web.Script.Services
Imports System.Web.Services
Imports System.Collections.Generic
Imports System.Text
Imports System.Drawing
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.IO
Imports ClassLibrary1
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService()> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ScriptService()> _
Public Class InvoiceHTMLService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetBillInvoiceHtmlData() As Object
Dim objDAOBill As DAOInvoice
Dim Obj As Object
objDAOBill = New DAOInvoice()
Obj = objDAOBill.GetBillInvoiceHtmlData()
Return Obj
End Function
End Class
I got the answer for it thanks everyone, I am posting the answer so it may can help others the service call from client side can be done by using the complete class name present in .asmx page.In my Case
<%# WebService Language="vb" CodeBehind="InvoiceHTMLService.asmx.vb" Class="App.InvoiceHTMLService" %>
So I have to call the service in following way:
function SendRequest() {
App.InvoiceHTMLService.GetBillInvoiceHtmlData(callback);
}
Related
I am facing a problem passing string to HTML page through javascript.
I have a window form,
A HTML file, where I have my Javascript and HTML code.
In the function in C# page, I have a string that I need to send to the HTML page through javascript. But I can not pass it. Please advise me.
Thanks
My C# method code below
private void Form1_Load(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("ProjectName.Maps.html"));
webBrowser1.DocumentText = reader.ReadToEnd();
***//pass getDefaultMap() value (str) to the javascript in Maps.html page.***
}
private string getDefaultMap()
{
string str;
str = (#"Exec SP_Map_Display #Opt=1");
return str ;
}
My HTML page is below
<body>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
***// Get the data from C# code str***
}
</script>
<input type="button" name="btnSubmit" value="Submit" />
<div id="dvMap">
</div>
</body>
Assuming this is WinForms since there's a WebBrowser control, to call C# code from the HTML page JavaScript can be accomplished with this minimum example:
Simple HTML page added to the root of the project and Properties was setup to Copy to Output Directory: Copy if newer this will ensure there's a simple page for testing:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
The JS function getLocations will call C# method SendLocations, the important parts are the Form1 class annotations and setting webBrowser1.ObjectForScripting = this :
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
Clicking the HTML button Call C# will show a popup with the return value from C# method
I am getting error while implementing Signalr in asp.net C# like:
Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
I am implementing signalr in visual studio 2010 and I have implemented same code before but that is working fine. Please help me to resolve this error.
My code is like this:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="SignalRTest._default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.0-rc1.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
$(function () {
var IWannaChat = $.connection.myChatHub;
IWannaChat.client.addMessage = function (message) {
$('#listMessages').append('<li>' + message + '</li>');
};
$("#SendMessage").click(function () {
IWannaChat.server.send($('#txtMessage').val());
});
$.connection.hub.start();
});
</script>
<div>
<input type="text" id="txtMessage" />
<input type="button" id="SendMessage" value="broadcast" />
<ul id="listMessages">
</ul>
</div>
</form>
</body>
</html>
my code behind is like this:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports Microsoft.AspNet.SignalR.Hubs
Imports Microsoft.AspNet.SignalR
Imports System.Net
Namespace SignalRChat
<HubName("myChatHub")> _
Public Class LetsChat
Inherits Hub
Public Sub send(message As String)
message = "User : " + Dns.GetHostName() + " User :" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + " Message : " + message
Clients.Caller.addMessage(message)
End Sub
End Class
End Namespace
my global.asax is like this:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
RouteTable.Routes.MapHubs()
End Sub
I would write this, to set the hook on the button once connection started:
$(function () {
var IWannaChat = $.connection.myChatHub;
IWannaChat.client.addMessage = function (message) {
$('#listMessages').append('<li>' + message + '</li>');
};
$.connection.hub.start().done(function() {
$("#SendMessage").click(function () {
IWannaChat.server.send($('#txtMessage').val());
});
});
}
I have a problem using Ext.Net 2.5 and App.Direct:
Ext.onReady(function() {
App.direct.GetAll({
success: function (result) {
currentMessageId = result;
}
});
});
The problem exist in body onload too.
When I Call the direct method in Ext.onReady it gives me this error: "Cannot Call GetAll of undefined."
But, when I call it instead a click button handler it works without problem.
So, the question is:
When App.direct is defined?
In the Page Sources you could see the following.
Ext.onReady(function () {
Ext.ns("App.direct");
Ext.apply(App.direct, {
TestDirectMethod: function (config) {
return Ext.net.DirectMethod.request("TestDirectMethod", Ext.applyIf(config || {}, {}));
}
});
});
It is how a DirectMethod is rendered to a browser.
As you can see it is inside an Ext.onReady function. So, your onReady function is executed before that.
You can force rendering of our onReady function before your one using a ResourcePlaceHolder.
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
[DirectMethod]
public void TestDirectMethod()
{
X.Msg.Alert("DirectMethod", "Hello from Server!").Show();
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
<ext:ResourcePlaceHolder runat="server" Mode="Script" />
<script>
Ext.onReady(function() {
App.direct.TestDirectMethod();
});
</script>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
</form>
</body>
</html>
Here is a description of possible options for a ResourcePlaceHolder's Mode.
i have default.aspx page and one user control.
usercontrol is having following code for multiple file uploads.
now the problem is when i add a file for upload that current context file is not giving me any value it is still zero i guess because it is rendering from user control.
what should i do?
My Usercontrol UPLOAD.ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FileUpload.ascx.cs" Inherits="FileUpload" %>
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
var i = 1;
$(document).ready(function () {
$("#addfile").click(function () {
$("#dvfiles").append("<input name=" + i + "fu type=file /><a href=#>remove</a><br>");
i++;
});
$("#dvfiles a").live('click', function () {
$(this).prev("input[type=file]").remove();
$(this).remove();
});
});
$(document).submit(function () {
var flag = true;
$("#dvfiles input[type=file]").each(function () {
if ($(this).val() == "") {
$(this).css("background", "Red");
flag = false;
}
});
return flag;
});
</script>
<div id="Fileuploader">
Attach a file..<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
</div>
UPLOAD.ASCX.CS
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection filecolln = Request.Files;
//here i don't get values of current files.
// this is zero. because of this following if condition failed
//please help here
if (filecolln.Count > 0)
{
for (int i = 0; i < filecolln.Count; i++)
{
HttpPostedFile file = filecolln[i];
if (file.ContentLength > 0)
{
file.SaveAs(ConfigurationManager.AppSettings["FilePath"] + System.IO.Path.GetFileName(file.FileName));
}
}
lblMessage.Text = "Uploaded Successfully!";
}
else
{
lblMessage.Text = "No files selected!";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
Default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%# Register TagPrefix="ucFileuploader" tagName="Fileuploader" src="FileUpload.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ucFileuploader:Fileuploader ID="Fileuploder" runat="server" />
</div>
</form>
</body>
</html>
The problem is that you are using javascript an id names.
so when you have control with id addfile in .aspx it is rendered as is,
but when you have control with id addfile in user control with id Fileuploader,
than the rendered id is Fileuploader_addfile,
so change id name in java script with the proper id.
To chechk what is name of rendered id, open page in browser, open source of the page and find you element and copy id into java script.
Change all ids in java script with rendered id names.
I would suspect it could be this line:
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
Which should be:
<script type="text/javascript" src="/_scripts/jquery-1.4.1.min.js"></script>
I’m having trouble getting JSON results working with Struts 2.2.1.1.
Does anyone have a simple working example that returns a JSON result to a JSP using Struts 2.2.1.1 and is ready to run in Eclipse as a dynamic web project?
Please include the struts.xml, action class and JSP code. Also, note dependencies. Thank you.
Here’s how to create a simple JSON example using the Struts 2 jQuery plugin.
Go to Struts2 jQuery Plugin Showcase
Navigate to Ajax Forms > Buttonset / Checkboxes
Review the code for Buttonset that was populated from AJAX JSON Result. This is code I selected to create a simple example.
Create dynamic web project in Eclipse
Create a Java package and name it test.
Download the Struts 2 jQuery plugin showcase source (struts2-jquery-showcase-x.x.x-sources.jar) and extract the JAR file.
Import Echo.java, JsonSample.java, and ListValue.java into the test package and move the code into the package with quick fix.
Change the class annotation in Echo.java and JsonSample.java to #ParentPackage(value = "test")
In addition to the standard Struts 2 libraries, ensure that the struts2-json-plugin-x.x.x.jar, struts2-jquery-plugin-x.x.x.jar, and struts2-convention-plugin-x.x.x.jar files are in your classpath.
Create a struts.xml file and add the following XML:
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.convention.action.packages" value="test" />
<package name="test" extends="json-default” namespace="/">
</package>
</struts>
Create an index.jsp file and insert the following code:
<s:form id="form2" action="echo" theme="xhtml">
<s:url id="remoteurl" action="jsonsample" />
<sj:checkboxlist href="%{remoteurl}" id=“remoteCheckboxlist” name="echo" list="languageList" label="Language" />
<sj:submit targets="formResult" value="AJAX Submit" indicator=“indicator” button="true"/>
</s:form>
Run the example.
Must see : struts2-x.x.x-all.zip /apps/struts2-showcase-2.2.1.war
Struts 2 and JSON example
Struts 2 autocompleter + JSON example
It is very simple to get Json work with struts2.
For this,
you need to add struts-json plugin*(jsonplugin-0.32.jar)* to classpath.
Your struts.xml file should extends json-default
<package name="base" namespace="/" extends="json-default">
Your action result be like this.
<result type="json"><param name="root">jsonData</param></result>
Inside action class, declare json as
private LinkedHashMap<K, V> jsonData new LinkedHashMap<k, V>();
and then add the result list to json like
jsonData.put("result", anyList or object);
Thats all we have to do. Then we can access the result using javascript.
Try this, will help you in Struts 2.0.14 with jsonplugin-0.32.jar.
struts.xml:
<struts>
<package name="example" extends="json-default">
<action name="HelloWorld" class="example.HelloWorld" >
<result type="json" />
</action>
<action name="HelloWorld1" class="example.HelloWorld" >
<result name="success" >example/HelloWorld.jsp</result>
</action>
</package>
</struts>
action class Helloworld.java:
package prabhakar;
import glb.DB;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Prabhakar
*/
public class HelloWorld {
private List<StateMaster> stateList= new ArrayList<StateMaster>();
private List<RegnMaster> regnList= new ArrayList<StateMaster>();
private Integer stateId;
public Integer getStateId()
{
return this.stateId;
}
public void setStateId(Integer stateId)
{
this.stateId=stateId;
}
public List<StateMaster> getStateList() {
return stateList;
}
public void setStateList(List<StateMaster> stateList) {
this.stateList = stateList;
}
public void setRegnList(List<RegnMaster> regnList) {
this.regnList = regnList;
}
public List<RegnMaster> getRegnList() {
return regnList;
}
public String execute() throws Exception {
stateList=DB.getStateData()//
if(stateId !=null)
{
regnList=DB.getRegnByStateId(stateId);
}
//setMessage(getText(MESSAGE));
return "success";
}
/**
* Provide default valuie for Message property.
*/
}
You can directly call HelloWorld.action to view the JSON data or else you can bind the JSON data to a form element below.
JSP page HelloWorld.jsp:
/*
Prabhakar
*/
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<script>
<%#include file="../js/jquery-1.7.1.min.js"%>
</script>
<html>
<!-- JavaScript Plugins -->
<script>
function getLoad(){
var stateId = $('#state').val();
$.getJSON('HelloWorld.action', {'stateId': stateId},
function(data) {
var divisionList = (data.regnList);
var options = $("#regn");
options.find('option')
.remove()
.end();
options.append($("<option />").val("-1").text("--Select--"));
$.each(divisionList, function() {
options.append($("<option />").val(this.regnId).text(this.regnName));
});
}
);}
</script>
<!-- jQuery-UI Dependent Scripts -->
<body>
State List <s:select name="stateId" list="stateList" id="state" listKey="stateId" onchange="getLoad()" listValue="stateName" headerKey="0" headerValue="--select--" />
Regn List <s:select name="regnId" list="regnList" listKey="regnId" id="regn" listValue="regnName" headerKey="0" headerValue="--select--" />
</body>
</html>
Happy coding :)