Postback event on text changed event - javascript

I want to postback on every keypress/textchanged event in textbox but my javascript is not running. Am i missing something...????
My Html textbox is this:
<asp:TextBox ID="Txt_Search" runat="server" AutoCompleteType="Disabled"
onkeypress="Postback();" OnTextChanged="Txt_Search_TextChanged" AutoPostBack="true">
</asp:TextBox>
My Javascript code is this:
function Postback() {
__doPostBack('<%= Txt_Search.ClientID %>', '');
};
My on textchanged event is this:
protected void Txt_Search_TextChanged(object sender, EventArgs e)
{
FolderStructure.Nodes.Clear();
Searchtxt();
}

I create sample projects ASP.NET WebForms and AJAX.
I Suggest you can use AJAX process .NET Generic Handler File. Please you research about Generic Handler file.
Before create Generic Handler file "Search.ashx" and Paste above the code.
public void ProcessRequest(HttpContext context)
{
var search = HttpContext.Current.Request.Form["term"];
//Dummy Data
List<string> searchList = new List<string> { "Red", "Orange", "Ping", "Blue", "White", "Black" };
string result = string.Empty;
if (!string.IsNullOrEmpty(search))
{
searchList = searchList.Where(x => x.ToLower().Contains(search.ToLower())).ToList();
if (searchList != null && searchList.Count() > 0)
{
foreach (var item in searchList)
{
result += "<li>" + item + "</li>";
}
}
}
else
{
result="<li> Not Found </li>";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
and Create Your Search Page, YourFile.aspx, my file name Search.aspx.
ASPX Page Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtSearch" class="js-search" value="Search" />
<div class="searchResult">
<ul>
</ul>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<script>
$(function () {
$(".js-search").on('keyup', function () {
var term = $('.js-search').val();
if (term.length > 2) {
sendSearchRequest({ "term": term });
}
});
function sendSearchRequest(value) {
var datas = $.ajax({
type: "POST",
url: '/Search.ashx',
cache: false,
async: false,
data: value,
success: function (term) {
$('.searchResult').empty();
$('.searchResult').append(term);
}
});
}
});
</script>
</body>
</html>
This example when all three letters entered send ajax request search.ashx file and contains search term and get result on search page.
I hope that helps.

Modify code as below and check
__doPostBack('Txt_Search', '');

here is demo for dynamic search in asp.net.
Your textbox should be:
<asp:TextBox ID="PopertyName" placeholder="Property Name" href="#"
propertyid="" runat="server" class="dropdownAnchor"
autocomplete="off" onkeydown="SearchProperty()"></asp:TextBox>
here we will call a function named searchProperty() onkeydown event.
so, your ajax should be,
function SearchProperty() {
$.ajax({
url: '<%=Page.ResolveUrl("~/Dashboard/NewDashboard.aspx/GetProperty") %>',
data: "{ 'prefix': '" + $("#PopertyName").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//Your code to bind result that received from your back end.
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
};
these function will call a GetPoprty() method on newDashboard.aspx.cs file.
so my back end method is,
[WebMethod]
public static List<Model.Property> GetProperty(string prefix)
{
// Here you get your text in prefix
}

Related

Success callback function JQUERY AJAX not working

I am trying to fetch password from database when username is provided .I am getting the result in POSTMAN, but the success callback function is not getting fired, even the error callback is also not working
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery/jquery-3.5.1.min.js"></script>
<script src="jquery/getpassword.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="dirtext" runat="server" ></asp:TextBox>
<asp:Button ID="dirsubmit" runat="server" Text="Button" OnClick="dirsubmit_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Given below the javascript file getpassword
$(document).ready(function () {
$('#dirsubmit').click(function () {
var x;
var objuser = {
name: $('#dirtext').val(),
};
var param = {
user: objuser
};
$.ajax({
type: "POST",
url: "WebForm4.aspx/GetPassList1",
data: JSON.stringify(param),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hi");
console.log(response);
var result = JSON.parse(response.d);
x = result;
},
error: function (response) {
console.log("error");
}
});
console.log(x);
});
});
Given below is the function GETPASSLIST1
[System.Web.Services.WebMethod]
public static string GetPassList1(User user)
{
using (var db = new userdetailsDBContext())
{
var queryStud = db.UserDetails.Where(s => s.name == user.name)
.Select(s => new { s.pass });
return JsonConvert.SerializeObject(queryStud);
}
}
This is the result I got on postman which indicates that api is working fine still the success or the error callback is not getting fired
{
"d": "[{\"pass\":\"$2a$11$iUGNxBof.6eka5XXSg7M1OR7sxy/enYK7wzF7TlSaaoJulxNcP0Um\"}]"
}
If I remove .click event then the success callback is working but after using .click event it doesn't work

Javascript autocomplete not working in ascx

I have a autocomplete in a grid-view in a ascx file but the autocomplete is not working in the ascx file. I have made several similar autocomplete in other page that work. Why is it that the autocomplete does not work in my ascx file. I have a hypotheses why it does not work but I am unsure how to fix it here it is
I think that the problem is with the following url in the javascript
url: "contratoGerencia.aspx/getSupplierAndComponente"
However I dont know how I should change it don get it to work with the ascx file.Also I found a solution here https://www.codeproject.com/Questions/757769/How-to-Call-Ascx-page-form-JavaScript-Funnction-Of that is almost what I want the only problem is that I also have a textbox in my situation.
Any help would be very appreciated. I hope the following information will help you.
Here is my ascx (ComponentesControler.ascx) code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="../css/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../scripts/autocomplete.js" ></script>
<asp:TextBox CssClass="gridContractAndComponente" ID="txtContractComponenteFooter" Text="" runat="server" TextMode="MultiLine" Rows="1" />
Here is my ascx.cs (ComponentesControler.ascx.cs) code
[WebMethod]
public static List<string> getSupplierAndComponente(string prefixText)
{
string lv_numero_contrato;
List<string> numeros_contrato = new List<string>();
connectionStringBuilder builder = new connectionStringBuilder();
String connString;
connString = builder.builder.ConnectionString;
string selectStatement = " SELECT numero_contrato FROM erp_contratos ";
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectStatement;
cmd.Parameters.AddWithValue("#searchText", prefixText);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lv_numero_contrato = reader.GetString(reader.GetOrdinal("numero_contrato"));
numeros_contrato.Add(lv_numero_contrato);
}
}
conn.Close();
}
}
return numeros_contrato;
}
Here is the aspx page (contratoGerencia.aspx) were I use the ascx file
<div id="ComponentesSection" class="menusection">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always" >
<ContentTemplate>
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Here is my javascript file (autocomplete.js)
$(document).ready(function () {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
The problem is in the name of your parameter entered in AJAX, your method expects to receive a parameter named prefixText and not containedText.
Change
data: {'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
with
data: {'prefixText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
The issue can be triggered by the UpdatePanel like explained here:
jQuery $(document).ready and UpdatePanels?
So modify your autocomplete.js like this:
$(document).ready(function() {
SearchSupplierAndComponente();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
See if the console error goes away.

calling a c# class method from html page

Can we call a C# method in a class from a html page??
I have a class names Crud.cs
public class Crud
{
public String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>
</head>
<body>
<div style="align-content:center;">
<input type="text" id="HtmlName" />
<button id="btn_gen_html" onclick="createHtml()">Generate</button>
</div>
<div id="Msg"></div>
<div id="feedbackMsg"></div>
<script>
function createHtml() {
var name = document.getElementById("HtmlName").value;
$.ajax({
type: "POST",
url: "Crud.cs/generateFiles",
data: { name } ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else(val==1)
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
}
</script>
</body>
</html>
This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?
You can't call normal method. The method must be static and web method.
Try this:
public class Crud
{
[WebMethod]
public static String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
You are missing a controler in your project.
You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.
Try looking for some MVC guides, Here is one from microsoft web site
You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.
Basic syntax
<script type="text/javascript"> //Default.aspx
function myfunction() {
$.ajax({
type: "POST",
url: 'Default.aspx/myfunction',
data: "mystring",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
Default.aspx.cs
[WebMethod]
public static String myfunction(string name)
{
return "Your String"
}
If you want to use page call without ajax: Ref
//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
return "Hello";
}
//aspx page
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(param1,onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById(‘lbl’);
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:
// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static String generateFiles(String name)
{
return generateHtml(name);
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):
$.ajax({
type: "POST",
url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
If ASP.NET MVC is used, use JsonResult to return JSON string as success result:
public class CrudController : Controller
{
[HttpPost]
public JsonResult generateFiles(String name)
{
return Json(generateHtml(name));
}
}
The AJAX call for the action method looks similar but the URL part is slightly different:
$.ajax({
type: "POST",
url: "Crud/generateFiles",
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
//Perfect solution
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
//PLEASE menntion [WebMethod] attribute on your method.

Accessing bulk array values in code behind using Ajax

I am passing values to code behind (C#). I had researched a lot and used this code, but it didn't work for me. Below is the code that I used.
I need to pass values in code behind (C#), but using this code I am getting an error near routes.EnableFriendlyUrls(settings); as:
Script:
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the Ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {values : JSON.stringify({ arr: values })},
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
HTML:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
Code:
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Though I had an error in code behind, I am not getting any error, and I am unable to go to code behind even after putting the break point. I am getting a button when I run this code, and when I click this not happen except the page is getting refreshed each time when I click the button. How can I do this?
Change:
var values = [1, 2, 3];//your array wasn't valid
data: {values : values},//you don't need to stringify the values because we have a valid json syntax

Can't Get jquery AJAX request to process

Hi I'm trying to do just a simple ajax call to a method in my code behind. At this point I'm just testing, so I'm keeping it as simple as possible, but it's always erroring. I'm sure it's just a simple mistake, but I have no idea what to do. It seems really straight forward, and it should work, but when I click the button, it just pops up an alert saying "[object Object]". Here is my code, any help is greatly appreciated:
aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="Program.TestPage" %>
<!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 type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnSubmit" value="Submit" />
</div>
</form>
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TestPage.aspx/InsertData",
dataType: "json",
data: "{}",
success: function (data) {
alert(data.d);
},
error: function (result) {
alert(result);
}
});
});
});
</script>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Web.Services;
namespace Program
{
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string InsertData()
{
string retMessage = "ddd";
return retMessage;
}
}
}
UPDATE
Sorry everyone, turns out the issue was in my global.asax. It was intercepting the ajax request, and messing everything up. Once I made sure the HTTP was a GET in the asax file, it stopped killing my ajax request, and started working.
In your javascript, you're calling InsertData as a POST
Try
[WebMethod]
[HttpPost]
public static JsonResult InsertData()
{
return Json(new { Message = "ddd" }, JsonRequestBehavior.AllowGet);
}
And in your javascript,
success: function (data) {
alert(data.Message);
},
You can try this:
var dataToPost = "{ country:'" + 2 + "', amount:" + 4.02 + "}";
$.ajax({
url: #Url.Action("PostAmount", "Deal")',
type: "POST",
dataType: 'json',
data: dataToPost,
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
alert("hi"+ data);
}
});

Categories

Resources