$(document).ready(function () {
$("#products").kendoMultiSelect({
placeholder: "Select products...",
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: {
type: "odata",
serverFiltering: true,
transport: {
read: {
url: "http://demos.kendoui.com/service/Northwind.svc/Products",
data: function () {
return {
text: $("#products").data('kendoMultiSelect').input.val()
};
}
}
}
}
});
});
Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts
Wednesday, November 8, 2017
Kendo MultiSelect Server Side Filtering

Tuesday, January 28, 2014
How to solve XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin error in ASP.NET MVC 4

This error may occur when you try to communicate between different domain using AJAX calls. To solve the issue we need set up the WEB API to return correct headers.
Create a class called CrossDomainActionFilter inherited by ActionFilterAttribute.
public class CrossDomainActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
bool needCrossDomain = true;
if (needCrossDomain)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
[AcceptVerbs("GET", "POST")]
[CrossDomainActionFilter]
public object GetTest()
{
rep = new ChatRepository();
chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);
System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
{
Data = box,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
return jsonResult.Data;
}
Create a class called CrossDomainActionFilter inherited by ActionFilterAttribute.
public class CrossDomainActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
bool needCrossDomain = true;
if (needCrossDomain)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
[AcceptVerbs("GET", "POST")]
[CrossDomainActionFilter]
public object GetTest()
{
rep = new ChatRepository();
chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);
System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
{
Data = box,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
return jsonResult.Data;
}
Friday, June 28, 2013
Pass object into to Controller Action Parameter through Jquery Ajax Call in ASP.NET MVC

Consider the below Developer class
Model:
public class Developer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
In our controller action we accept a developer object.
Controller:
[HttpPost]
public ActionResult FirstAjax(Developer developerobj)
{
string a = developerobj.FirstName;
string b = developerobj.LastName;
return Json(a+" "+b, JsonRequestBehavior.AllowGet);
}
View:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/MyController/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: JSON.stringify({ developerobj: { FirstName: "chamara", LastName: "janaka"} }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
Output:
Model:
public class Developer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
In our controller action we accept a developer object.
Controller:
[HttpPost]
public ActionResult FirstAjax(Developer developerobj)
{
string a = developerobj.FirstName;
string b = developerobj.LastName;
return Json(a+" "+b, JsonRequestBehavior.AllowGet);
}
View:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/MyController/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: JSON.stringify({ developerobj: { FirstName: "chamara", LastName: "janaka"} }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
Output:
Friday, April 12, 2013
How to return JSON string from ASP.NET WebMethod

Recently i worked with making some ajax calls to the server. There we need to get the response from the server as a JSON string. I have used two ways of returning a JSON string from a ASP.NET WebMethod.
Method 1 - Uses the JavaScriptSerializer
[WebMethod]
public string GetLankanList()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Lankans> lankanList = new List<Lankans>();
string[] names = { "chamara", "janaka", "asanka" };
for (int i = 0; i < names.Length; i++)
{
Lankans srilankans = new Lankans();
srilankans.Name = names[i];
lankanList.Add(srilankans);
}
string jsonString = serializer.Serialize(lankanList);
return jsonString;
}
Method 2 - Uses ScriptMethod with the WebMethod
[WebMethod]
Method 1 - Uses the JavaScriptSerializer
[WebMethod]
public string GetLankanList()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Lankans> lankanList = new List<Lankans>();
string[] names = { "chamara", "janaka", "asanka" };
for (int i = 0; i < names.Length; i++)
{
Lankans srilankans = new Lankans();
srilankans.Name = names[i];
lankanList.Add(srilankans);
}
string jsonString = serializer.Serialize(lankanList);
return jsonString;
}
Method 2 - Uses ScriptMethod with the WebMethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getData()
{
try
{
string name="chamara";
return name;
return name;
}
catch (Exception ex)
{
throw ex;
}
}
Sunday, March 24, 2013
Using the jQuery $.ajax() Method in a Web Forms Application

The WCF service that converts temperature values between Celsius and Fahrenheit is shown below.
namespace AjaxWebForm
{
[DataContract]
public class TemperatureData
{
Notice that Convert() is decorated with an [WebInvoke] attribute. Due to this attribute, Convert() becomes callable from the client-side jQuery code. The RequestFormat and ResponseFormat properties of the [WebInvoke] attribute specify JSON as the communication format during request and response, espectively. The Method property specifies that Convert() can be invoked by HTTP POST requests. The Service class implements Convert(). The Convert() method checks the Unit of the incoming TemperatureData object and, depending on the Unit, converts the Value to the other scale.
The Service class’s Convert() method can be called using jQuery’s $.ajax() function as shown below
namespace AjaxWebForm
{
[DataContract]
public class TemperatureData
{
[DataMember]
public decimal Value { get; set; }
public decimal Value { get; set; }
[DataMember]
public string Unit { get; set; }
}
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
TemperatureData Convert(TemperatureData t);
}
public class Service : IService
{
public TemperatureData Convert(TemperatureData t)
{
if (t.Unit == "C")
{
t.Value = (t.Value * 1.8m) + 32;
t.Unit = "F";
}
else
{
t.Value = (t.Value - 32) / 1.8m;
t.Unit = "C";
}
return t;
}
}
}
The TemperatureData class represents the data contract of the WCF service and contains two data member properties: Value and Unit. The IService interface represents a service contract for the service and defines a single method Convert(). The Convert() method accepts a TemperatureData object and returns a TemperatureData object after converting the temperature value to the other scale.
public string Unit { get; set; }
}
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
TemperatureData Convert(TemperatureData t);
}
public class Service : IService
{
public TemperatureData Convert(TemperatureData t)
{
if (t.Unit == "C")
{
t.Value = (t.Value * 1.8m) + 32;
t.Unit = "F";
}
else
{
t.Value = (t.Value - 32) / 1.8m;
t.Unit = "C";
}
return t;
}
}
}
The TemperatureData class represents the data contract of the WCF service and contains two data member properties: Value and Unit. The IService interface represents a service contract for the service and defines a single method Convert(). The Convert() method accepts a TemperatureData object and returns a TemperatureData object after converting the temperature value to the other scale.
Notice that Convert() is decorated with an [WebInvoke] attribute. Due to this attribute, Convert() becomes callable from the client-side jQuery code. The RequestFormat and ResponseFormat properties of the [WebInvoke] attribute specify JSON as the communication format during request and response, espectively. The Method property specifies that Convert() can be invoked by HTTP POST requests. The Service class implements Convert(). The Convert() method checks the Unit of the incoming TemperatureData object and, depending on the Unit, converts the Value to the other scale.
The Service class’s Convert() method can be called using jQuery’s $.ajax() function as shown below
Using $.ajax() to Call the WCF Service Convert() Method
$(document).ready(function () {
$("#Button1").click(function () {
url = "Service.svc/Convert";
data = '{"Value":"' + $("#Text1").val() + '","Unit":"' + $("#Select1").val() + '"}';
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
});
The Convert button’s click event handler contains the jQuery code for invoking the Convert() method. The $.ajax() function has many configurable settings. The url setting allows you to specify the remote resource URL. For a WCF service, the URL takes the form <path_to_svc_file>/<method_name>.
The type option lets you specify the HTTP request type to be used while making the request. The Convert() method is configured with the [WebInvoke] attribute to use a POST method, and hence type is POST. The data setting indicates the data to be sent to the server (if any) while making the call. Notice how data is captured in JSON format. A JSON object takes the form of key-value pairs: a key and its value are separated by a colon (:), and multiple key-value pairs are delimited by a comma (,).
The dataType setting governs the data type of the response (XML, JSON, and so on). Recollect that the [WebMethod] attribute specified ResponseFormat as JSON, so dataType here must be set to JSON to correctly process the data coming from the server.
If Convert() returns successfully, the function specified by the success option (OnSuccess) is called. If there is any error while calling the WCF service, a function specified by the error option (OnError) is called. The OnSuccess() function is where you process the data returned from the WCF service. OnSuccess() receives the return value of Convert() (the TemperatureData object) as a parameter. You can access its Value and Unit properties and display an alert box to the user.
In the OnError() function, you typically flag the error to the user or take some corrective action. OnError() receives an error object; you can display its status and statusText properties to the user. Figure shows a sample run of the Web Forms application.

$(document).ready(function () {
$("#Button1").click(function () {
url = "Service.svc/Convert";
data = '{"Value":"' + $("#Text1").val() + '","Unit":"' + $("#Select1").val() + '"}';
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
});
The Convert button’s click event handler contains the jQuery code for invoking the Convert() method. The $.ajax() function has many configurable settings. The url setting allows you to specify the remote resource URL. For a WCF service, the URL takes the form <path_to_svc_file>/<method_name>.
The type option lets you specify the HTTP request type to be used while making the request. The Convert() method is configured with the [WebInvoke] attribute to use a POST method, and hence type is POST. The data setting indicates the data to be sent to the server (if any) while making the call. Notice how data is captured in JSON format. A JSON object takes the form of key-value pairs: a key and its value are separated by a colon (:), and multiple key-value pairs are delimited by a comma (,).
The dataType setting governs the data type of the response (XML, JSON, and so on). Recollect that the [WebMethod] attribute specified ResponseFormat as JSON, so dataType here must be set to JSON to correctly process the data coming from the server.
If Convert() returns successfully, the function specified by the success option (OnSuccess) is called. If there is any error while calling the WCF service, a function specified by the error option (OnError) is called. The OnSuccess() function is where you process the data returned from the WCF service. OnSuccess() receives the return value of Convert() (the TemperatureData object) as a parameter. You can access its Value and Unit properties and display an alert box to the user.
In the OnError() function, you typically flag the error to the user or take some corrective action. OnError() receives an error object; you can display its status and statusText properties to the user. Figure shows a sample run of the Web Forms application.

Tuesday, January 22, 2013
Ajax AutoCompleteExtender

One of the many control extenders in the ASP.NET AJAX Control Toolkit is the AutoCompleteExtender, which allows you to show a list of suggestions while a user types in another control (such as a text box). Figure 25-9 shows the AutoCompleteExtender at work on an ordinary TextBox control. As the user types, the drop-down list offers suggestions. If the user clicks one of these items in the list, the corresponding text is copied to the text box.
To create this example, you need an ordinary text box, like this:
Contact Name:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Next, you need to add the ScriptManager and an AutoCompleteExtender control that extends the text box with the autocomplete feature. The trick is that the list of suggestions needs to be retrieved from a specialized code routine called a web method, which you need to create in your page.
Here’s an example of how you might define the AutoCompleteExtender. It uses the TargetControlID property to bind itself to the txtName text box, and it sets the MinimumPrefixLength property to 2, which means autocomplete suggestions won’t be provided until the user has entered at least two characters of text. Finally, the ServiceMethod property indicates the web method you’re going to use is named GetNames(). Before you can run this page, you need to create that method.
<ajaxToolkit:AutoCompleteExtender ID="autoComplete1" runat="server"
TargetControlID="txtName" ServiceMethod="GetNames" MinimumPrefixLength="2">
</ajaxToolkit:AutoCompleteExtender>
The next step is to create the GetNames() web method. Here’s the basic method you need to add to the code-behind class of your web page:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static List<string> GetNames(string prefixText, int count)
{ ... }
The web method accepts two parameters, which indicate the text the user has typed so far and the desired number of matches (which is ten by default). It returns the list of suggestions. The two attributes that precede the GetNames() method indicate that it’s a web method (meaning the client should be allowed to call it directly with HTTP requests) and that it supports JavaScript calls (which is what the AutoCompleteExtender uses).
Actually writing the code that retrieves or generates the suggestion list can be quite tedious. In this example, the code retrieves the list of name suggestions from the Northwind database.
List<string> names = null;
// Check if the list is in the cache.
if (HttpContext.Current.Cache["NameList"] == null)
{
// If not, regenerate the list.
names = GetNameListFromDB();
// Store the name list in the cache for sixty minutes.
HttpContext.Current.Cache.Insert("NameList", names, null,
DateTime.Now.AddMinutes(60), TimeSpan.Zero);
}
else
{
// Get the name list out of the cache.
names = (List<string>)HttpContext.Current.Cache["NameList"];
}
...
With the list in hand, the next step is to cut down the list so it provides only the ten closest suggestions. In this example, the list is already sorted. This means you simply need to find the starting position—the first match that starts with the same letters as the prefix text. Here’s the code that finds the first match:
...
int index = -1;
for (int i = 0; i < names.Count; i++)
{
// Check if this is a suitable match.
if (names[i].StartsWith(prefixText))
{index = i;}
break;
}
// Give up if there isn't a match.
if (index == -1) return new List<string>();
...
The search code then begins at the index number position and moves through the list in an attempt to get ten matches. However, if it reaches the end of the list or finds a value that doesn’t match the prefix, the search stops.
...
List<string> wordList = new List<string>();
for (int i = index; i < (index + count); i++)
{
// Stop if the end of the list is reached.
if (i >= names.Count) break;
// Stop if the names stop matching.
if (!names[i].StartsWith(prefixText)) break;
wordList.Add(names[i]);
}
...
Finally, all the matches that were found are returned:
...
return wordList;
You now have all the code you need to create the effect shown in Figure.
Monday, January 21, 2013
The ScriptManager in ASP.NET

In order to use ASP.NET AJAX, you need to place a new web control on your page. This control is the ScriptManager, and it’s the brains of ASP.NET AJAX. Like all ASP.NET AJAX controls, the ScriptManager is placed on a Toolbox tab named AJAX Extensions. When you can drag the ScriptManager onto your page, you’ll end up with this declaration:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
At design time, the ScriptManager appears as a blank gray box. But when you request a page that uses the ScriptManager you won’t see anything, because the ScriptManager doesn’t generate any HTML tags. Instead, the ScriptManager performs a different task—it adds the links to the ASP.NET AJAX JavaScript libraries. It does that by inserting a script block that looks something like this:
<script src="/YourWebSite/ScriptResource.axd?d=RUSU1mI ..."
type="text/javascript">
</script>
This script block doesn’t contain any code. Instead, it uses the src attribute to pull the JavaScript code out of a separate file. However, the ScriptManager is a bit craftier than you might expect. Rather than use a separate file to get its JavaScript (which would then need to be deployed along with your application), the src attribute uses a long, strange-looking URL that points to ScriptResource.axd. ScriptResource.axd isn’t an actual file—instead, it’s a resource that tells ASP.NET to find a JavaScript file that’s embedded in one of the compiled .NET 3.5 assemblies. The long query string argument at the end of the URL tells the ScriptResource.axd extension which file to send to the browser.
Tuesday, January 1, 2013
How to Call Server Side Method from Client Side


In the example we are going to write a method to get the current time as a server side method, make an AJAX call to the server and executes the GetCurrentTime method.
Below is our HTML markup. TextBox to enter name and a button to execute the call
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
Below is our client side code.
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST", // Request type
url: "Jquery.aspx/GetCurrentTime", //Page URL/Method name
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', // parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,//success method
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
Below is our server side code. Note that this method is declared as static and a WebMethod
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
Below is our client side code.
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST", // Request type
url: "Jquery.aspx/GetCurrentTime", //Page URL/Method name
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', // parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,//success method
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
Below is our server side code. Note that this method is declared as static and a WebMethod
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Sunday, December 9, 2012
Check String availability using ASP.NET and Jquery.


In this post we are going to use Jquery to check whether a string is exists in a given list. You can also use this method to check the string availability in your database table as well.
First add a handler class to your project and name it as "LoginHandler.ashx"
<%@ WebHandler Language="C#" Class="LoginHandler" %>
using System;
using System.Web;
public class LoginHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string uname = context.Request["uname"];
string result = "0";
if (uname != null)
{
result = CheckAvailability(uname);
}
context.Response.Write(result);
context.Response.End();
}
public string CheckAvailability(string name)
{
string result = "0";
System.Collections.Generic.List<string> lst = new System.Collections.Generic.List<string>();
lst.Add("chamara");
lst.Add("janaka");
lst.Add("lahiru");
foreach (string item in lst)
{
if (item == name)
{
result = "1";
break;
}
}
return result;
}
public bool IsReusable
{
get
{
return false;
}
}
}
CheckAvailability()
This method accepts the parameter uname from POST method and check the string through the list. Then it returns the string "0" if the parameter value not exists in the list or "1" if it exists.
Below is our web form
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.8.3.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
$("#btnAvailability").click(function () {
$.post("LoginHandler.ashx", { uname: $("#<% =txtName.ClientID %>").val() }, function (result) {
if(result=="1")
{
$("#dvMsg").html("Name already taken!");
}
else if (result == "0") {
$("#dvMsg").html("Available");
}
else {
$("#dvMsg").html("Error!");
}
});
});
$("#btnAvailability").ajaxError(function (event, request, settings, error) {
alert("Error requesting page " + settings.url + " Error:" + error);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input type="button" id="btnAvailability" value="Check Availability" />
<div id="dvMsg"></div>
</div>
</form>
</body>
</html>
We pass the text in "txtName" as a POST parameter to the handler and gets the response to the "result" variable then display the message according to the result.
Saturday, December 8, 2012
Simple Ajax Jquery Call example in ASP.NET

Read the post Simple Ajax Call example in ASP.NET to get an idea about making an asynchronous ajax call to the server. Below code will make an asynchronous call to the server using ajax and Jquery.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.8.3.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
$("#btnchange").click(function () {
$.get("GetData.aspx", function (response) {
document.getElementById("myDiv").innerHTML = response;
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" id="btnchange">Change Content</button>
</div>
</form>
</body>
</html>
$.get() or $.ajax()
Uses the XMLHttpRequest from JavaScript behind the scenes.
Create a new page called GetData.aspx and add the below code in page load event.
GetData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
Response.Expires = -1;
Will keep the page from being cached in the browser.
The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:
Response.ContentType = "text/plain";
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.8.3.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
$("#btnchange").click(function () {
$.get("GetData.aspx", function (response) {
document.getElementById("myDiv").innerHTML = response;
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" id="btnchange">Change Content</button>
</div>
</form>
</body>
</html>
$.get() or $.ajax()
Uses the XMLHttpRequest from JavaScript behind the scenes.
Create a new page called GetData.aspx and add the below code in page load event.
GetData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
Response.Expires = -1;
Will keep the page from being cached in the browser.
The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();

Simple Ajax Call example in ASP.NET

Go through the sample code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function GetasyData() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "GetData.aspx", true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="GetasyData()">Change Content</button>
</form>
</body>
</html>
Create a new page called GetData.aspx and add the below code in page load event.
GetData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
All modern browsers like IE7+, Firefox, Chrome, Opera and Safari has built-in XMLHttpRequest object.
xmlhttp = new XMLHttpRequest();
will create the new XMLHttpRequest object. Old browsers uses ActiveX object.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.readyState == 4
xmlhttp.status == 200
HTTP state is OK.
xmlhttp.open("GET", "GetData.aspx", true);
xmlhttp.send();
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server)
Sending a large amount of data to the server (POST has no size limitations)
Sending user input (which can contain unknown characters), POST is more robust and secure than GET
Response.Expires = -1;
Will keep the page from being cached in the browser.
The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:
Response.ContentType = "text/plain";
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function GetasyData() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "GetData.aspx", true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="GetasyData()">Change Content</button>
</form>
</body>
</html>
Create a new page called GetData.aspx and add the below code in page load event.
GetData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
All modern browsers like IE7+, Firefox, Chrome, Opera and Safari has built-in XMLHttpRequest object.
xmlhttp = new XMLHttpRequest();
will create the new XMLHttpRequest object. Old browsers uses ActiveX object.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
will create the new ActiveX object.
xmlhttp.readyState == 4
0: The request is uninitialized (before you've called open()).
1: The request is set up, but not sent (before you've called send()).
2: The request was sent and is in process (you can usually get content headers from the response at this point).
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4: The response is complete; you can get the server's response and use it.
xmlhttp.status == 200
HTTP state is OK.
xmlhttp.open("GET", "GetData.aspx", true);
Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
xmlhttp.send();
Send the request to the server.
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server)
Sending a large amount of data to the server (POST has no size limitations)
Sending user input (which can contain unknown characters), POST is more robust and secure than GET
Response.Expires = -1;
Will keep the page from being cached in the browser.
The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();

Subscribe to:
Posts (Atom)
