I have a webservice that returns an object
[WebMethod]
public List<User> ContractorApprovals()
I also have a webservice that accepcts an object
[WebMethod]
public bool SaveContractor(Object u)
When I make my webservice calls via Jquery:
function ServiceCall(method, parameters, onSucess, onFailure) {
var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json
$.ajax({
type: "POST",
url: "services/"+method,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (typeof onSucess == 'function' || typeof onSucess == 'object')
onSucess(msg.d);
},
error: function(msg, err) {
$("#dialog-error").dialog('open');}
});
I can call the first one just fine. My onSucess function gets passed a javascript object exactly structured like my User object on the service.
However, I am now having trouble getting the object back to the server.
I'm accepting Object as a parameter on the server side so I can't inagine there is an issue there. So I'm thinking something is wrong with the parms on the client side but i'm not sure what...
I am doing something to the effect
ServiceCall("AuthorizationManagerWorkManagement.asmx/ContractorApprovals",
"",
function(data,args){$("#div").data('user',data[0])},
null)
then
ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
JSON.stringify({u: $("#div").data("user")}) //dont work $("#div").data('user'), //These also do not work: "{'u': ' + $("#div").data("user") + '}", NOR JSON.stringify({u: userObject})
function(data,args){(alert(data)},
null)
I know the first service call works, I can get the data. The second one is causing the "onFailure" method to execute rather then "OnSuccess".
Any ideas?
UPDATE:
I chaed my last code block to use : JSON.stringify({u: $("#div").data("user")})
I now get Invalid object passed in, member name expected. (1):
But I have no idea what the means... Google has turned up plenty of that error, but no problem like mine...
ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
"{u: " + JSON.stringify($("#div").data("user")) + "}",
function(data, args) { alert(data); },
FailedServiceCall);
Ok I have posted the code as well as a link over Click here!
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
$(document).ready(function() {
$('#txtAutoSuggest').keyup(function() {
var str = $("#txtAutoSuggest").val();
var a = JSON.stringify({ name: str });
CallService(a);
});
});
function CallService(a) {
$.ajax({
type: "POST",
url: url,
data: a,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
$('#lblResult').text(data.d);
},
error: Error
});
}
function Error(request, status, error) {
$('#lblResult').text("Not Matched");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtAutoSuggest" runat="server"></asp:TextBox>
<asp:Label ID="lblResult" Text=" " Width="100%" runat="server" />
</div>
</form>
</body>
</html>
OR
application.js
var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
$(document).ready(function() {
$('#txtAutoSuggest').keyup(function() {
var str = $("#txtAutoSuggest").val();
var a = JSON.stringify({ name: str });
CallService(a);
});
});
function CallService(a) {
$.ajax({
type: "POST",
url: url,
data: a,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
$('#lblResult').text(data.d);
},
error: Error
});
}
function Error(request, status, error) {
$('#lblResult').text("Not Matched");
}
<%# WebService Language="C#" Class="WebService" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX or JQuery.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public string HelloWorld(string name)
{
Utility ut = new Utility(); // some class where you will have your database connection
ArrayList suggestedProblemName = ut.getItems(name); // some method of the class
return ""+suggestedProblemName[0];
}
}
Related
I can't access webmethod within javascript. It gives the error in the title. Why might it be caused?
Js :
function funcGoster() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// document.getElementById('text').innerHTML =
},
error: function (e) {
alert("başarısız" + e);
}
});
}
</script>
WebMethod :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public static string HelloWorld()
{
return "Hello World";
}
}
Ok, what you have looks quite good, but note in the web service page, you have to un-comment the one line.
so, you should have this:
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
Ok, now our code and markup:
<asp:Button ID="Button1" runat="server" Text="Button" Width="153px"
OnClientClick="ajtest();return false;"/>
<br />
</div>
<script>
function ajtest() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(' back from ajax message = ' + msg.d)
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
</script>
So, we also assume you have jQuery setup for this page? You need that.
You can call the web method without jQuery.
So, pure JavaScript, you could use this:
// Web method call without jQuery
function ajtest2() {
// ajax call without jquery
var xhr = new XMLHttpRequest()
xhr.open('POST', '/WebService1.asmx/HelloWorld')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send('{}');
xhr.onload = function () {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText)
alert(' back form ajaxes message = ' + userInfo.d)
}
}
}
I am developing a quite large application. But I am facing problem in Ajax. For that I tried to make a new and short program to invoke Ajax for test purpose. But I am stuck in that.
Here is the Test.aspx code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
Ajax function is
$(document).ready(function () {
$("#Button1").click(function () {
var text = $("#TextBox1").val();
text = "this is test";
debugger
$.ajax({
type: "POST",
contentype: "application/json; charset=utf-8",
url: "Test.aspx/Test",
data: { str: text},
//dataType:"json",
success: function (data) {
alert("yes");
},
error: function (response) {
debugger
alert(response);
}
});
return false;
});
});
And Test.aspx.cs code is below
[WebMethod]
public void Test(string str)
{
Console.WriteLine(str);
}
When I put some value in TextBox. It alerts Yes!. But does not invoke [WebMethod].
Anyone know the problem.
Make your [WebMethod] static as
[WebMethod]
public static void Test(string str)
{
//Console.WriteLine(str);
string retstr=str;
}
change ajax data value to data: "{'str':'" + text + "'}"
UPDATE
Try This Same Code
aspx:
<asp:Button ID="Button1" ClientIDMode="Static" runat="server" Text="Button" />
aspx.cs
[WebMethod]
public static void Test(string str)
{
string abc=str;//Use this wherever you want to, check its value by debugging
}
test.js
$(document).ready(function () {
$("#Button1").click(function () {
var text = "this is test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Test.aspx/Test",
data: "{'str':'" + text + "'}",
dataType:"json",
success: function (data) {
alert("yes");
},
error: function (response) {
alert(response);
}
});
});
});
This is working
C#
[WebMethod]
public static string Test(string str)
{
return str;
}
JS
const text = "this is test";
$.ajax({
url: "Test.aspx/Test?str="+text,
contentType: "application/json; charset=utf-8",
method: 'post',
data: "{'str':'"+text+"'}",
success: function (data) {
console.log(data);},
error: function (response) {
debugger;
console.log(response); }
});
Have you tried setting ScriptMethod attribute for your method like so:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
I'm trying to use a jquery autocomplete script within an asp.net project somebody else wrote. Although i can run it in a seperated project, it doesn't do anything when implemented inside the project i mentioned. They both are on .net 4.0 framework. html code of the page is like this:
<%# Page Title="" Language="C#" MasterPageFile="~/site.master" AutoEventWireup="true" CodeFile="Meslek.aspx.cs" Inherits="AutoComplete.Scripts_Meslek" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#ContentPlaceHolder1_txtCountry").autocomplete({
source: function (request, response) {
var param = { keyword: $('#ContentPlaceHolder1_txtCountry').val() };
$.ajax({
url: "Meslek.aspx/GetCountryNames",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
<div>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<br />
</asp:Content>
I think the problem is this row below should invoke the function to retrieve the autocomplete words from code behind, but whatever i enter into the textbox, nothing happens.
$("#ContentPlaceHolder1_txtCountry").autocomplete({
I know the code works becuase i use it in different projects, but when i implemented it on this project, i got nothing. I know the List that is returned form the code behind works and if i could call the function there, i am sure that i will retrieve the results.
So the question is, what might be the cause of this? Is this caused by some project properties, is it caused by the master page, is my code to invoke the function is wrong or is it something else?
The entire code in Meslek.aspx is below
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace AutoComplete
{
public partial class Scripts_Meslek : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string[] GetCountryNames(string keyword)
{
List<string> country = new List<string>();
//string query = string.Format("SELECT DISTINCT Country FROM Customers WHERE Country LIKE '%{0}%'", keyword);
string query = string.Format("SELECT mslk FROM meslek WHERE mslk LIKE '%{0}%'", keyword);
using (SqlConnection con =
//new SqlConnection("Data Source=KMISBPRDSQL001; Database=SIRIUS; Initial Catalog=SIRIUS; Trusted_Connection=True; "))
new SqlConnection(WebConfigurationManager.ConnectionStrings["SIRIUS"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
country.Add(reader.GetString(0));
}
}
}
return country.ToArray();
}
}
}
I suggest using this:
use function :
function CompleteText() {
$(document).ready(function () {
$(".Country").autocomplete({
source: function (request, response) {
var param = { keyword: $('.Country').val() };
$.ajax({
url: "Meslek.aspx/GetCountryNames",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
}
In TextBox:
<asp:TextBox ID="txtCountry" onfocus="CompleteText()" runat="server" class="Country" Width="298px"></asp:TextBox>
I have an array in JS and I am using following function to send it to aspx page
var array = [] //I want this array to be sent with JSON.
function result()
{
var jsonText = JSON.stringify({ list: array });
$.ajax({
type: "POST",
url: "test.aspx",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert("it worked"); },
failure: function () { alert("Uh oh"); }
});
}
And I am calling it on click of a button in asp, like this:
<asp:Button id="submitbtn" runat="server" OnClick="Button1_Click" OnClientClick="result()" />
But it isn't working. So, whats the exact way to do it?
Please try below code it will work for you
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="demotest.aspx.cs" Inherits="Web.demotest" %>
<!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="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var array =[[48.154176701412744,11.551694869995117],[48.15131361676726,11.551694869995117],[48.15555092529958,11.549291610717773]]
function result() {
var jsonText = JSON.stringify({ list: array });
$.ajax({
url: "demotest.aspx/Demo", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonText,
success: function (data) { alert("it worked"); },
error: function () { alert("Uh oh"); }
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="submitbtn" runat="server" Text="Ajax Call" OnClientClick="javascript:return result();" />
</div>
</form>
</body>
</html>
Write below code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace Web
{
public partial class demotest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void Demo(double[][] list)
{
//Write code here
}
}
}
For datatype use in c#.Please see the below picture
It does seem like it wouldn't be possible since callback functions seem to be page specific but in case it's possible I'd like to do that.
You can call static page methods marked with the WebMethod attribute using ASP.NET Ajax if you configure the ScriptManager to do so:
<form id="form" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
.
.
.
</form>
[WebMethod]
public static int Foo(string bar)
{
return 42;
}
Then in your client-side code:
function callFoo(bar)
{
return PageMethods.Foo(bar);
}
You can also do the same with jQuery:
function callFoo(bar)
{
$.ajax({
type: "POST",
url: "YourPage.aspx/Foo",
data: {
"bar": bar
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(message) {
// Do something.
}
});
}