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
Related
I am trying to search company names using jquery. If search parameter does not exists in employee list, it should returns all companies. When I put breakpoint to GetCompanyList, it could not hit. But I am getting JavaScript runtime error: Unable to get property 'length' of undefined or null reference
How can I solve this error? By the way I have no idea Javascript. I have just used it for my project. Thanks your help
Demo.aspx.cs
public partial class Demo : System.Web.UI.Page
{
static List<string> allCompanyName = new List<string>() { "ankara", "adana", "istanbul" };
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetCompanyName(string pre)
{
var response = allCompanyName.Any(i => i.StartsWith(pre));
return allCompanyName;
}
}
Demo.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Demo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
$('#<%=txtCompanyName.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
url: "Demo.aspx/GetCompanyName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Auto Complete Textbox without using Web Service</h3>
<table>
<tr>
<td>Type Company Name: </td>
<td>
<div class="ui-widget" style="text-align:left">
<asp:TextBox ID="txtCompanyName" runat="server" Width="350px" CssClass="textboxAuto" Font-Size="12px" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I have a simple WebMethod call that does not return anything. I receive no errors.
The code is very simple. I just wonder if there is a setting (IIS, webconfig, etc.) that is not correct. I have VS Pro 2013, Framework = 4.5 and IIS 10.0 Express.
Any thoughts on why my "Hello World!" program does not work?
JavaScript.aspx.cs
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 WebApplication1
{
public partial class JavaScript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetData()
{
return "Hello World!";
}
}
}
JavaScript.aspx.cs
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication1.JavaScript" %>
<!DOCTYPE html>
<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"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "JavaScript.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
</script>
</head>
<body>
<form id="frm" method="post">
<div id="Content">
</div>
</form>
</body>
</html>
Since I cannot post images (Not enough Reputation Points), please click this link to see my Network Tab:
Here is the Network Tab
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 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];
}
}