$(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.
Subscribe to:
Posts (Atom)