.Net, Ajax, ASP.NET, C#, HTML, JavaScript, JQuery, Kendo UI, Programming, Web Development, WebForms

Example of Binding a Kendo UI KendoNotification Control with an ASP.NET WebMethod

The notification effects brought to the Web-development table by Telerik’s Kendo UI Notification component are really cool. You can have a look at a running demo of some of the neat stuff you can do with Kendo UI Notifications on the Telerik demo site at:

http://demos.telerik.com/kendo-ui/notification/index

In my case, I wanted to see how easy it would be to plug the Kendo UI Notification control into an ASP.NET Webform. Why use a WebForm you might ask? Well, I think there’s still something to be said for RAD and quickly prototyping a Web page. Webforms work really nicely for that.

Anyhow, regardless of my reasons for using Webforms, the entire process turned out to be fairly straightforward to do using a JQuery .Ajax connection to an ASP.NET WebMethod.

A Little Background, Including what the Example Page Below Looks Like When Running

Most examples that I’ve seen are primarily either client-side or server side and don’t show an example of an end-to-end solution, so in this article I’m taking a stab at showing what it looks like to put together a Notification control with an ASP.NET DropDownList control, that checks with a server-side ASP.NET WebMethod for the validity of the value of the DropDownList control each time the user selects a different option or clicks a button to check.

So just to summarize here is the business logic of the example page:

  1. The example Web page has a DropDownList and a Button on it.
  2. When you change the DropDownList or click on the button, a JavaScript event is triggered
  3. The JavaScript creates a JSON list of parameters
  4. The JQuery calls an ASP.NET WebMethod via a .AJAX connection
  5. The WebMethod returns an OK message or an Error message to the JavaScript calling function
  6. A green Kendo UI Notification with a five second existance is shown if the WebMethod returned an OK
  7. A permanent red Kendo UI Notification is shown if the WebMethod returned an error message
  8. The Kendo UI Notification messages stack underneath the DropDownList being validated
  9. If an error happens connecting to the WebMethod, a detailed error message is alerted

 For Starters, Let’s Import the Kendo UI Libraries and Associated Components

Ok, like the title above says, before we do anything, let’s import everything we’ll need to add Kendo UI components to our Web page. This also includes JQuery since Kendo UI relies on it. For this example I’m including these imports as links directly from Web-hosted libraries. But for a larger project, you’ll probably want to download the components and include them with your Web project.

 <link href="http://cdn.kendostatic.com/2014.1.416/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.1.416/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://cdn.kendostatic.com/2014.1.416/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.1.416/js/kendo.ui.core.min.js"></script>

The WebForm Components

Ok, now let’s include the ASP.NET WebForm DropDownList and button components. These will trigger JavaScript that calls a function that we’ll call testNotificationFunction(). Also, and very importantly, we’ll need to add a <span or a <div tag that we can hook up our Kendo UI Notification control to. Let’s call this span tag popupNotification

<span id="popupNotification"></span>
<asp:DropDownList ID="DropDownList1" runat="server" onchange="testNotificationFunction()">
<asp:ListItem Value="0" Text="Option #0"></asp:ListItem>
<asp:ListItem Value="1" Text="Option #1"></asp:ListItem>
<asp:ListItem Value="2" Text="Option #2"></asp:ListItem>
<asp:ListItem Value="3" Text="Option #3"></asp:ListItem>
</asp:DropDownList><div id="container"></div><br>
<input id="Button2" type="button" value="button" onClick="testNotificationFunction();"/>

Adding the JavaScript Function

Now comes the main part of the process: the JavaScript that will call the ASP.NET WebMethod, and that will display the Kendo UI Notification.

For starters, let me note that I ended up calling my ASP.NET Web page TestKendoNotification.aspx On that page, I added an ASP.NET WebMethod called Update that we will call via a JQuery .AJAX call.

Checking the DropDownList SelectedValue

For starters, we need to get the Selected value and text from the ASP.NET DropDownList. Here’s the example syntax to do this in JQuery:

// Get the value and the text of the selected dropdownlist option
var passThisId = $("#<%= DropDownList1.ClientID %> option:selected").val();
var passThisText = $("#<%= DropDownList1.ClientID %> option:selected").text();

As you can see, we use inline ASP.NET code to get the rendered ClientID of the DropDownList. This is a better idea than hard-coding the Id since differing versions of ASP.NET can and will render controls with different ID naming conventions. Think of this as a way of future-proofing your code.

The rest of the syntax are straightforward JQuery calls to get the value and text of the selected option.

Setting up the Parameters to Send

The next step is to package up the parameters that we’re going to send to our ASP.NET WebMethod via a .AJAX call. A simple way to do this is to instantiate a JavaScript variable to which you assign the parameters as properties in a string. Then to get the parameters into a JSON-friendly format, use the JQuery command: JSON.stringify 

Here’s what this code looks like for our example:

// set up the parameter(s) to pass to the server-side code as an object. In this example only the id and value are passed.
 var pageElements = JSON.stringify({
 SelectedId: passThisId,
 SelectedValue: passThisText
 });

Writing the .AJAX Call

Now we’ll set up our .AJAX call to the ASP.NET WebMethod. Here’s the basic syntax of the important part of the call from our example:

$.ajax({
type: 'POST',
url: 'TestKendoNotification.aspx/Update',
data: pageElements,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {

The type is naturally set to POST. Then as you can see, the URL is set to the name of our ASP.NET Web page, followed by the name of our ASP.NET WebMethod, which in our case is called Update:

url: 'TestKendoNotification.aspx/Update',

Then we set the parameters to send over to our ASP.NET WebMethod as:

data: pageElements,

Followed by some fairly common practice parameters:

contentType: 'application/json; charset=utf-8',
dataType: 'json',

After which we can handle the success or failure of the .AJAX call in the parameters:

success: function (msg) {

and

}, error: function (msg) {

 Setting up the ASP.NET WebMethod

Now we’ll want to handle the server-side of things. In this example this doesn’t involve much except returning an Ok message for every value except for Option #1, which will return an error message. In a more realistic example this would hold more validation logic and likely a database call.

Here is the example WebMethod written in C#:

 [System.Web.Services.WebMethod]
public static string Update(string SelectedId, string SelectedValue)
{
string returnValue = "Ok";
if (("1").Equals(SelectedId)) {
returnValue = "The first option was selected.<br>This is a problem that needs to be fixed.";
}
return returnValue;
}

Handling a Successful Server-Side Call and Calling the Kendo UI Notification Component

Below is the code for handling a success scenario. This involves decision logic where a green Kendo UI Notification is shown if the server sent back an Ok message, while a red Notification is shown if the server sent back an error.

success: function (msg) {
// show a different color based on the results of the server-side query
if (msg.d == 'Ok') {
// If the message is Ok then allow it to hide itself after 5 seconds.
// Otherwise if there was an error, show the message permanently
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: dropdownToCheck, autoHideAfter: 5000, width: 400
}).data('kendoNotification');
popupNotification.show(msg.d, 'success');
} else {
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: dropdownToCheck, autoHideAfter: 0, width: 400
}).data('kendoNotification');
popupNotification.show(msg.d, 'error');
}
}

As you can see from this code, the green Ok message is appended to our DropDownList control and hides itself after 5 seconds:

var popupNotification = $('#popupNotification').kendoNotification({
appendTo: dropdownToCheck, autoHideAfter: 5000, width: 400
}).data('kendoNotification');
popupNotification.show(msg.d, 'success');

Alternately, the red warning message is shown appended to our DropDownList control, but it does not fade away over time… it requires a click from the user to be removed.

var popupNotification = $('#popupNotification').kendoNotification({
appendTo: dropdownToCheck, autoHideAfter: 0, width: 400
}).data('kendoNotification');
popupNotification.show(msg.d, 'error');

Handling an Error in the Connection to the ASP.NET WebMethod

Setting up descriptive error messages is actually a very useful part of your AJAX call, especially if you are running into troubles communicating with your WebMethod. Another useful tool is to run Fiddler so that you can check what your calls to the WebMethod actually look like. Remember that your JavaScript parameters and WebMethod parameters should match… including their upper/lower case formats.

Here is the error handling in the example below. Notice how we can get the responseText of the returned error object in order to see more details about what went wrong:

, error: function (msg) {
// use msg.respponseText in order to see a descriptive error message.
alert('problem' + msg.responseText);
}

The Example ASP.NET WebForm/Kendo UI Notification

I’ve described the separate components of this example in the article above, including the desired behavior. Let me know if you have any questions about it that I haven’t answered. Happy coding!

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd " >
<script runat="server">
[System.Web.Services.WebMethod]
public static string Update(string SelectedId, string SelectedValue)
{
string returnValue = "Ok";
if (("1").Equals(SelectedId)) {
returnValue = "The first option was selected.<br>This is a problem that needs to be fixed.";
}
return returnValue;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml " >
<head runat="server">
<link href="http://cdn.kendostatic.com/2014.1.416/styles/kendo.common.min.css " rel="stylesheet" / >
<link href="http://cdn.kendostatic.com/2014.1.416/styles/kendo.default.min.css " rel="stylesheet" / >
<script src="http://cdn.kendostatic.com/2014.1.416/js/jquery.min.js " ></script>
<script src="http://cdn.kendostatic.com/2014.1.416/js/kendo.ui.core.min.js " ></script>
<title></title>
<script>
function testNotificationFunction() {
// Get the value and the text of the selected dropdownlist option
var passThisId = $("#<%= DropDownList1.ClientID %> option:selected").val();
var passThisText = $("#<%= DropDownList1.ClientID %> option:selected").text();
// set up the parameter(s) to pass to the server-side code as an object. In this example only the id and value are passed.
var pageElements = JSON.stringify({
SelectedId: passThisId,
SelectedValue: passThisText
});
$.ajax({
type: 'POST',
url: 'TestKendoNotification.aspx/Update',
data: pageElements,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// show a different color based on the results of the server-side query
if (msg.d == 'Ok') {
// If the message is Ok then allow it to hide itself after 5 seconds.
// Otherwise if there was an error, show the message permanently
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: dropdownToCheck, autoHideAfter: 5000, width: 400
}).data('kendoNotification');
popupNotification.show(msg.d, 'success');
} else {
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: dropdownToCheck, autoHideAfter: 0, width: 400
}).data('kendoNotification');
popupNotification.show(msg.d, 'error');
}
}, error: function (msg) {
// use msg.respponseText in order to see a descriptive error message.
alert('problem' + msg.responseText);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
Either changing the dropdown value, or clicking the button causes a call to server-side validation<br>
<span id="popupNotification"></span>
<asp:DropDownList ID="DropDownList1" runat="server" onchange="testNotificationFunction()">
<asp:ListItem Value="0" Text="Option #0"></asp:ListItem>
<asp:ListItem Value="1" Text="Option #1"></asp:ListItem>
<asp:ListItem Value="2" Text="Option #2"></asp:ListItem>
<asp:ListItem Value="3" Text="Option #3"></asp:ListItem>
</asp:DropDownList><div id="container"></div><br>
<input id="Button2" type="button" value="button" onClick="testNotificationFunction();"/>
</form>
</body>
</html>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s