Monday, February 13, 2012

Simple ajax with asp.net

Here is a simple example of ajax using asp.net.

Create a asp.net web project named AjaxTest. In defaut.aspx page add the following code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AjaxTest._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
var xmlhttp = null;
function ShowSuggestions(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Search.aspx?q=" + str;
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
</script>
<h2>
Welcome to ASP.NET AJAX!
</h2>
<input type="text" id="txt1″" onkeyup="ShowSuggestions(this.value)" />
<p>
Suggestions: <span id="txtHint"></span>
</p>
</asp:Content>
--------------------------------------------

Add a page named Search.aspx

Add the following code in the code behind page

protected void Page_Load(object sender, EventArgs e)
{
var sugtext = new List<string>();
sugtext.Add("Rayhan");
sugtext.Add("Tonmoy");
string suggestion = (from sgText in sugtext
where sgText.StartsWith(Request.QueryString["q"])
select sgText).FirstOrDefault();
//string suggestion="Hello";
if (string.IsNullOrEmpty(suggestion))
Response.Write("No Suggestion Found");
else
Response.Write(suggestion);
Response.End();
}

 

 

Build and see the action.

No comments:

Post a Comment

What is DaemonSet in Kubernetes

 A DaemonSet is a type of controller object that ensures that a specific pod runs on each node in the cluster. DaemonSets are useful for dep...