Channels ▼
RSS

Open Source

Supercharging ASP.NET Web Form Apps


Adding JavaScript to Call the API

So, now I have an Web API method and I've defined the routing. The last step to hook up the new feature is to add JavaScript in the HTML to call the API.

To modify the GridView control to render an interactive checkbox instead of rendering True or False text, I can replace the BoundField in the GridView control markup with a TemplateField. This TemplateField has an ItemTemplate that contains an ASP.NET checkbox control as well as a hidden field (Listing Three).

Listing Three: The Updated GridView Markup

<asp:GridView runat="server" ID="tasksGrid" AutoGenerateColumns="False"
  DataKeyNames="TaskID"
  OnRowEditing="editTask">
  <Columns>
    <asp:BoundField DataField="TaskName" ItemStyle-Width="200px" HeaderText="Task"/>
    <asp:TemplateField ItemStyle-Width="100px" HeaderText="Is Complete?">
      <ItemTemplate>
        <asp:CheckBox ID="isCompleteCheck" runat="server" 
           Checked='<%#Eval("IsComplete") %>' />
        <asp:HiddenField ID="taskIdField" runat="server" 
           Value='<%#Eval("TaskId") %>'/>
      </ItemTemplate>
    </asp:TemplateField>
    <asp:CommandField ShowEditButton="True" EditText="Edit" />
  </Columns>
</asp:GridView>

The Checkbox control is bound to the IsComplete property of the Task object, and the hidden field is bound to the TaskId property. The page now renders interactive checkboxes as shown in Figure 4.

Super-Charging ASP.NET Web Form Apps
Figure 4: Updated Tasks page.

I now have interactive checkboxes, and I can use jQuery to wire up the click event of the checkbox to call the new Web API method, as in Listing Four.

Listing Four: jQuery to Call the Web API UpdateStatus Method

(function ($) {
    $(document).ready(function () {
        $('input[name$="isCompleteCheck"]').click(function() {
            var $check = $(this);
            var $hidden = $check.parent().children('input[name$="taskIdField"]');
            var taskId = $hidden.val();

            $.ajax({
                type: "PUT",
                cache: false,
                url: 'api/Tasks/UpdateStatus/' + taskId.toString()
            }).done(function (msg) {
               alert("Task Updated: " + msg);
            });
        });
    });

} (jQuery));

This is pretty standard jQuery. I wire up the click event of the checkboxes in the GridView by using the "Attribute ends with" selector input[name$="isCompleteCheck"]. In the same way, I then obtain the relevant hidden field for that checkbox, and use the jQuery val() method to obtain the taskID of the selected checkbox. Finally, I use jQuery's ajax method to build the relevant call to the Web API method.

Note that I use the PUT HTTP method and create the URI discussed earlier in the article: api/Tasks/UpdateStatus/{id}. If the call is successful, the user is notified using a JavaScript alert dialog.

Taking it Further

I have only scratched the surface of what can be done with the Web API, but this example demonstrates that it is possible to add rich client-side functionality using the ASP.NET Web API with existing Web Forms applications. In the GridView control, I am still using server-side data binding to do the initial rendering of the list. But rather than do a full post-back to the server just to update the IsComplete status, I added some simple JavaScript and a very simple AJAX call (combined with a Web API action method) to add client-side functionality. This provides a much more modern and responsive application.

This approach is an effective strategy for enhancing existing ASP.NET applications. I don't need to start from scratch and do a total rewrite in order to add some of these newer technologies. As emerging features are required, they can be added using jQuery and the ASP.NET Web API. Also, over time, legacy code could be adjusted to take advantage of this new approach. There are JavaScript libraries (such asKnockoutJS, Backbone, and Breeze) that can simplify the code as more and more of the logic is pushed to the client.

At DotNetNuke, we used this approach: We have a fundamental dependency on ASP.NET Web Forms and it is not feasible to rewrite everything to use ASP.NET MVC or the ASP.NET Web API. However, we were able to add a new Services Framework that is built on the Web API to provide this more modern functionality to third-party extension writers, as well as our own first-party extensions.


Charles Nurse has been a Senior Architect for DotNetNuke Corporation, the creators of the DotNetNuke Open Source Web Application Platform, since 2006. He is a Microsoft ASP.NET MVP and an ASPInsider.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video