Textbox letter content check - c#

I'm writing a C# project,
One of my needs is to expose button when TextBox (not dynamic) have more then 1 letter, As long as i know changes (which includes functions activation) will happen only between postacks.
Is there any possibilty to check the Texbox letter content without using postback (Includes skip on page load function).
Thanks Ahead.

Is there any possibilty to check the Textbox letter content without
using postback (Includes skip on page load function).
Assuming you are using ASP.NET Web Form, you could call WebMethod via Ajax.
After posting back to server via Ajax,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="TextBox1" />
<button type="button" onclick="postData();">Post Data</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function postData() {
var data = { text: $('#<%= TextBox1.ClientID %>').val() };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postdata") %>',
data: JSON.stringify(data),
contentType: 'application/json',
success: function (msg) {
$('#<%= TextBox1.ClientID %>').val(msg.d);
}
});
}
</script>
</form>
</body>
</html>
Code Behind
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostData(string text)
{
return text + DateTime.Now;
}
}
}

Related

can not get data form function using ajax jquery in asp.net c#

i am trying use $.ajax() method in asp.net to fill a html tag but i didn't get any data from on success parameter
i am calling getData function from c# code and I tried to return a string but it doesn't work i also tried to user Response.write() but the same issue
when I alert returned value it show me the aspx page code
as following image
here is my code
Default.apsx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#firstDrop").on("change", function () {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
data: { id: $("#firstDrop").val() },
success: function (data) {
alert(data);
$("#secondDrop").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select runat="server" id="firstDrop">
<option value="0">first select</option><option value="1">second select</option><option value="3">third select</option>
</select>
<select id="secondDrop"></select>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string getData()
{
return"<option>ABC</option><option>CDE</option>";
}
}
Basic rule when creating a webmethod in asp.net.
Your method should be static.
You need to decorate your function with System.Web.Services.WebMethod.
C# Code Behind
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Javascript (Aspx)
Here, in your case make your getdata function static and webmethod as well. When calling the webmethod through ajax use data.d to read the response.
[System.Web.Services.WebMethod]
public static string getData(int id)
{
return "<option>ABC</option><option>CDE</option>";
}
$("#firstDrop").on("change", function() {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
dataType: "json",
data: {
id: $("#firstDrop").val()
},
success: function(data) {
alert(data.d);
$("#secondDrop").html(data.d);
}
});
});
Reference Site:
https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Similar thread "Calling webmethod in webform"
calling-a-webmethod-with-jquery-in-asp-net-webforms

Adding a newline character to InnerText property of div

I have a button click event that should take the text from a text box and then write to the InnerText property of a div on the same page. The text is getting inputted to the div, but it's never on a new line. I've tried the following variations:
EDIT: To the person who chose to close this question, this is inside of a div and not inside a multi-line text box. They don't work the same, because I had this working when I was using a multi-line text box.
protected void Button1_Click(object sender, EventArgs e)
{
if (txtCategory.Text.Length > 0)
{
StringBuilder sb = new StringBuilder(drugTerms.InnerText);
sb.AppendLine(txtCategory.Text);
drugTerms.InnerText = sb.ToString();
txtCategory.Text = "";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (txtCategory.Text.Length > 0)
{
StringBuilder sb = new StringBuilder(drugTerms.InnerText);
sb.Append(txtCategory.Text).Append(Environment.NewLine);
drugTerms.InnerText = sb.ToString();
txtCategory.Text = "";
}
}
aspx
<%# Page Language="C#" AutoEventWireup="true" Inherits="_Default" Codebehind="Default.aspx.cs" %>
<!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 id="Head1" runat="server">
<title>AutoComplete Text Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<link href="StyleSheet1.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'CategoryName':'" + document.getElementById('txtCategory').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (x) {
alert("Error Occurred");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">
Enter Drug Name:
</label>
<asp:Button ID="Button2" runat="server" OnClick="Button1_Click" Text="Button 2" />
<asp:TextBox ID="txtCategory" CssClass="auto" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button 1" />
<div id="drugTerms" runat="server"></div>
</div>
</div>
</form>
</body>
</html>
and I tried to add an html break line character in their as well. Every time when the button is clicked the text in the text box is added with the new term being a space instead of the newline character. Why can't I add a new line character in this div?
use "<br>" instead of Environment.NewLine
have you tried using a new Literal and a PlaceHolder?
the aspx:
<asp:PlaceHolder ID="ph" runat="server' visible="true"></asp:PlaceHolder>
then your code behind would look something like this:
c#:
Literal literal = new Literal();
lit.Text = "<br/>";
ph.Controls.Add(lit);
I actually do like #I4V's solution of using a break over the environment newline.

How can i implement textbox auto suggest using jquery in my c# asp.net application?

I want to implement jquery textbox auto suggest in my c# asp.net application for the purpose of searching employees.Now i am using ajax auto suggest in my application but it's seems to be slow when data more than 50000 thousand.Somebody please help me.If any great idea about faster serching with huge data without using indexing please share with me.
jQuery Auto search details given bellow : Put down this code in your .aspx file. Here txtSearchBox is search box name.
<%# 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 id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtSearch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel>
<ContentTemplate>
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" AutoCompleteType="Search"> </asp:TextBox>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Now .cs file details:
public partial class _Default : Page
{
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=devserver;Initial Catalog=Catalog;Persist Security Info=True;User ID=userName;Password=Password"))
{
using (SqlCommand cmd = new SqlCommand("select (strEmployeeName + ',' + strEmployeeCode) as username from tblEmployee where strEmployeeName LIKE '%'+#SearchText+'%' ", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["username"].ToString());
}
return result;
}
}
}
}
If you wish you can use object data source like:In this case your object method should return List type data.
[WebMethod]
public static List<string> GetAutoCompleteData(string strSearchKey)
{
AutoSearch_BLL objAutoSearch_BLL = new AutoSearch_BLL();
List<string> result = new List<string>();
result = objAutoSearch_BLL.AutoSearchEmployeesData(strSearchKey);
return result;
}
jQuery UI provides a good autocomplete implementation and the docs suggest it can be used to pull autocomplete suggestions from very large databases
You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.
http://jqueryui.com/demos/autocomplete/
Note that if you are returning 50K suggestions to the browser (as opposed to pulling suggestions from a pool of 50K possibilities), you are doing something wrong (that's a lot of data to push across the wire).
Implementing jQuery UI autocomplete would be simple as this
$(function(){
$( "#txtEmployee" ).autocomplete({
source: "employees.aspx",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
jQuery UI autocomplete supports some client side caching of the data. That will definitely improve the speed of search. Also, you may consider implementing a caching layer in your application where you store the List of Employees so that the autocomplete will not query your database everytime. Instead it will fetch the data from the caching layer.

jquery datepicker & c#/aspnet - asynchronous database query

I am working with the C#, ASP.NET framework [very new to this environment]. This is what I want to achieve:
Pass data from jQuery Datepicker textbox to controller
Parse the date, database query from the selected range
Asynchronously, send queried rows back to page to update content
Here is the HTML:
<form id="date" runat="server">
<asp:Label AssociatedControlId="from_date" Text="From:" runat="server" />
<asp:TextBox ID="from_date" Text="" runat="server" />
<asp:Label AssociatedControlId="to_date" Text="To:" runat="server" />
<asp:TextBox ID="to_date" Text="" runat="server" />
</form>
I have this snippet on the client side to handle the change event:
var dates = $('#from_date, #to_date').datepicker({
if ( this.id == "to_date" )
$('#to_date').change();
});
To call in the controller:
protected void to_date_UpdateHandler( object sender, EventArgs e ) {
/* from here, I would query within the ranges in the "from_date"
and "to_date" textboxes */
}
Obviously, this will cause a page refresh, but I want to pass the data along asynchronously. How should I go about achieving this? Thank you.
It's a little unclear from your question which particular jQuery 'datepicker' plugin you are using, so I will proceed to use the jQuery UI date picker for this example.
First off, there are some things you should be aware of when working with jQuery and ASP.NET WebFroms. Specifically, up until very recently, when server controls are rendered, their IDs get mangled by .NET. It is usually a good idea to stick to CSS classes when doing lots of client side scripting, but if you must use IDs, you can select controls like so:
var $toDate = $('input[id$=to_date]');
Secondly, you will need to communicate with the server via WebMethods or by configuring an ASPX page to return XML or JSON. ASP.NET MVC really makes this easy, but it's possible in WebForms and definitely worth your time (I despise UpdatePanels).
Now to some code.
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>Example ASP.NET/jQuery Datepicker</title>
<link type="text/css" rel="stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/redmond/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript" src=" http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.js"></script>
<script type="text/javascript">
// On DOM ready...
$(function() {
// Cache the date pickers
var $fromPicker = $('.from_date'),
$toPicker = $('.to_date');
// Init the date pickers
$fromPicker.datepicker();
$toPicker.datepicker();
// Handle change event for 'to' date
$toPicker.change(function(e) {
// Get the dates
var fromDate = $fromPicker.datepicker('getDate');
var toDate = $(this).datepicker('getDate')
// prepare the data to be passed via JSON
var dates = {
fromDate: fromDate,
toDate: toDate
};
// Call the web method
$.ajax({
type: 'POST',
url: 'Default.aspx/GetDate',
data: $.toJSON(dates),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert(msg.d);
}
});
});
// Log errors
$(".log").ajaxError(function() {
$(this).text("Error in ajax call.");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<asp:Label ID="from_date_lbl" AssociatedControlID="from_date" Text="From:" runat="server" />
<asp:TextBox ID="from_date" CssClass="from_date" Text="" runat="server" />
<asp:Label ID="to_date_lbl" AssociatedControlID="to_date" Text="To:" runat="server" />
<asp:TextBox ID="to_date" CssClass="to_date" Text="" runat="server" />
<asp:Label ID="log_lbl" CssClass="log" runat="server" />
</form>
</body>
</html>
ASPX.CS
using System;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public static string GetDate(string fromDate, string toDate)
{
DateTime dtFromDate;
DateTime dtToDate;
// Try to parse the dates
if (DateTime.TryParse(fromDate, out dtFromDate) &&
DateTime.TryParse(toDate, out dtToDate))
{
// Perform calculation and/or database query
return "success!";
}
return null;
}
}

Call non-static method in server-side from client-side using JavsScript

How do I call a non-static method in server side(aspx.cs) from client side using javascript (aspx)....?
As far as I know I can call static method in server side from client side...
server side:
[WebMethod]
public static void method1()
{
}
client side:
<script language="JavaScript">
function keyUP()
{
PageMethods.method1();
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
It works. Now how do I call non-static method from client side?
You can avoid the static constraint by using a simple .asmx page instead of the codebehind page.
1) Open New Website using the AJAX Enable ASP.NET template (it puts the necessary references in the web.config)
2) SIMPLESERVICE.ASMX - Add a new .asmx web service (I called mine SimpleService.asmx)
Notice the [System.Web.Script.Services.ScriptSerive] decoration and that the SimpleService class implements Webservice.
<%# WebService Language="C#" Class="SimpleService" %>
using System;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public class SimpleService : WebService
{
[WebMethod]
public string GetMessage(string name)
{
return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
}
}
3) DEFAULT.ASPX - To use it reference the service in you script manager and you are off and running. In my Javascript I call the class.method - SimpleService.GetMessage.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function callServer() {
SimpleService.GetMessage($get("Name").value, displayMessageCallback);
}
function displayMessageCallback(result) {
$get("message").innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/SimpleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
</div>
<h1>Hello World Example</h1>
<div>
Enter Name: <input id="Name" type="text" />
Call Server
<div id="message"></div>
</div>
</form>
</body>
</html>
I used the example I found from Scott Gu
Found Here.
No you cannot call non-static methods from client side per se. I've tried it once but it is ugly one (also I used jQuery ajax). Just call the page using ajax with method name appended to it as query string parameter and then on server side check the parameter and call the relevant method. But as I've told you it is pretty ugly :(
$.ajax({'/mypage.aspx?m=mymethod',......}); //this is not correct syntax
on server side:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString.HasKeys() ||
string.IsNullOrEmpty(Request.QueryString["m"]))
{
//return error or something relevant to your code
}
var m = Request.QueryString["m"];
switch(m)
{
case "a":
a();
break;
.....
.....
}
}
Actually, you don't get to call non-static methods in this way.
When you are calling a PageMethod, you're basically calling a special web service. This feature only works with static methods on the same page.
C#
public string LoadString() {
return "my string";
}
JS/jQuery
$('#txt').val(<%= LoadString() %>);
as an answer to Pramulia
i think you want to have a function with an argument from the client side which is implemented in the example -> CallServer(arg1, arg2)
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Implements Interface="System.Web.UI.ICallbackEventHandler" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>Client Callbacks</title>
<script runat="server">
public void RaiseCallbackEvent(String eventArgument)
{
// Processes a callback event on the server using the event
// argument from the client.
}
public string GetCallbackResult()
{
// Returns the results of a callback event to the client.
string dateString = DateTime.Now.ToLongDateString();
return dateString;
}
void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
</script>
<script type="text/javascript">
function ReceiveServerData(arg, context) {
Message.innerText = "Date from server: " + arg;
}
</script>
</head>
<body>
<h2>Client Callbacks Without Postbacks</h2>
<form id="form1" runat="server">
<input type="button" value="Callback"
onclick="CallServer('1', alert('Callback sent to Server'))" />
<br />
<span id="Message"></span>
</form>
</body>
</html>
If you want to call it using the same function, you can use the following code:
[WebMethod]
public static void method1()
{
ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
obj.yourFunctionName(ParametersIfAny);
}
I ended up using hidden fields in case anyone reads this. I can set the value in c# under a function and then read it in javascript.
Dave has written in detail about calling page methods from client side using jquery ajax. The general idea is like this (if you find any problem please refer to Dave's site).
C# Code:
[WebMethod]
public static string yourmethod(/*params*/)
{
return "Hello World!"
}
ASPX:
$.ajax({
type: 'POST',
data: /*Your Data*/,
dataType: 'JSON',
contentType: 'application/json',
url: '/yourpage.aspx/yourmethod',//Method to call
success: function(result, status) {
//handle return data
},
error: function(xhr, status, error) {
//handle error
}
});

Categories

Resources