Ajax Call in Asp.net ([WeBMethod] Function not calling) - javascript

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)]

Related

Auto complete in asp.net using jquery

Here I'm trying to use jquery auto complete in asp.net, I'm trying to retrieve the data from sql data source and use that for auto fetch. while I running the code auto complete have not worked.
my code
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtPartno').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
textbox field
<asp:TextBox ID="txtPartno" CssClass="Textboxbase" class="autosuggest" runat="server"></asp:TextBox>
and my c# code
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=MYPC-GN\\KASPLDB;Integrated Security=False;User ID=sa;Password=*****;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT PART_NO from Inventory where UserName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
One problem which I can see is your javascript call is little wrong. You cannot get the value of textbox which is created by asp itself with document.getElementById('txtPartNo'). To get this value, you will have to get it's client id which you can get using-
txtPartNo.ClientID so finally this will become-
data: "{'username':'" + document.getElementById('<%= txtPartno.ClientID %>').value + "'}",
If you don't try this way then you will not get the actual value of that textbox and undefined will be sent to the C# method which will not return anything.
First you should check if the JavaScript function it's getting called.
If it's getting called then you should check if the url is correct.
You can check in developer tools/ firebug etc. to see what request are you sending.
I did as follows:
ajaxCallSetting.js
var ajaxCallSetting = function (element, message, req) {
var baseInfo = {
baseUrl: "http://localhost:10266/"
};
var buildUrl= function() {
return baseInfo.baseUrl + message;
};
var callApi = function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: buildUrl(),
data: JSON.stringify(req),
dataType: "json"
}).success(function(data) {
response(data.d);
});
};
return {
init: function() {
$(element).autocomplete({
source: callApi
});
}
};
};
The head tag:
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
<script src="ajaxCallSetting.js"></script>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function () {
var req = {
username: $('#txtPartno').val()
};
apiSettings('#txtPartno', "Default.aspx/GetAutoCompleteData", req).init();
});
</script>
</head>
As far as possible,
Keeping separate Html code with the code in JavaScript is useful.
I don't think your TextBox is being hooked up properly. Try this:
<asp:TextBox ID="txtPartno" CssClass="Textboxbase autosuggest" runat="server"></asp:TextBox>
And try this in your JavaScript:
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + request.term + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});

ASP.NET/C# Error - passing value from drop down list via ajax

I am trying to link two drop down lists using JQuery AJAX, but I'm not getting anything.
My ASP.NET code for the drop downs is:
<td>Park*</td><!-- PARK -->
<td>
<asp:DropDownList class="form-control" ID="parkDDL" ClientIDMode="Static" onchange="ShowCurrentBuilding()" style="width:150px;" runat="server">
<asp:ListItem text="ALL" value="ALL"></asp:ListItem>
<asp:ListItem text="Central" value="C"></asp:ListItem>
<asp:ListItem text="West" value="W"></asp:ListItem>
<asp:ListItem text="East" value="E"></asp:ListItem>
</asp:DropDownList>
</td>
<td>Building </td><!-- BUILDING -->
<td>
<asp:DropDownList class="form-control" AutoPostBack="true" ID="buildingDDL" runat="server" style="width:300px;" OnSelectedIndexChanged="buildingToRoom"></asp:DropDownList>
</td>
My code for the JQuery in between JS tags (As you can see, I'm not quite sure how to output what is returned to the drop down list):
function ShowCurrentBuilding() {
$.ajax(
{
type: "POST",
url: "CreateRequest.aspx/GetCurrentBuilding",
data: '{name: ' + $('#<%= parkDDL.ClientID %> option:selected').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
I have also tried the following which i put in the document ready function :
$(document).ready(function () {
$('#<%=parkDDL.ClientID %>').on("change",function ShowCurrentBuilding() {
$.ajax(
{
type: "POST",
url: "CreateRequest.aspx/GetCurrentBuilding",
data: '{name: "' + $(this).find("option:selected").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessBuilding,
failure: function (response) {
alert(response.d);
}
});
});
function OnSuccessBuilding(response) {
alert(response.d);
}
});
Finally, here is my C# code:
namespace Team11
{
public partial class CreateRequest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate my initial drop down lists etc
}
}
//here is the function that is called in the JQuery function
[System.Web.Services.WebMethod]
public string GetCurrentBuilding(string name)
{
string textbx = "";
textbx = name;
return textbx;
}
I just want to filter the drop down list via ajax so the page doesn't reload with AutoPostBack = "true".
Thanks in advance to anyone that can help!!
Use the client side function, onchange, instead of server side, OnSelectedIndexChanged.

jQuery Autocomplete Doesn't Invoke For Textbox in ASP.NET

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>

JS not working on click of an asp:Button

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

How to not able to hit the controller in my asp.net mvc application using this code

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
GOTO = function () {
alert("yes");
$.ajax({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
My Controller ActionResult is something like this
JsonResult
[HttpPost]
public System.Web.Mvc.JsonResult Index(FormCollection collection)
{
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}
I am not able to return the JsonResult here allways I am getting popupmessage saying u have choosen to open this dialogue? is there something I am doing wrong?
thanks
Try this instead -- and make sure jQuery is loaded first. Note the changes to apply the handler via jQuery instead of inline, serializing the data, generating the URL in code dynamically rather than hard-coded, and returning false from the click handler to prevent normal form submission.
<script type="text/javascript">
$(function() {
$('input[type=button]').click( function() {
var data = $('form').serialize(); // or however you get your data
$.ajax({
cache: false,
type: "POST",
url: "<%= Html.Action( "index", "home" ) %>",
data: data,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
return false; // don't do the normal submit
});
});
</script>
<input type="button" value="submit" />
you need to put the button in a form tag and call the GOTO function in onsubmit event
It looks like your data: datastring might be the problem. Check to make sure that the name of your data parameter is the same as your method parameter.
I would try to approach it more like this ...
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$(form).submit(function() {
alert("yes");
$.post({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
});
}
</script>
<form>
// your form fields
<input type="button" value="submit" />
</form>
</asp:Content>
And then your controller should look more like this.
Notice how we changed the parameter to a string that matches your jQuery data field.
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
// you can deserialize your Json here.
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}

Categories