this.Blog.Find(entry => entry.IsHelpful);
 Saturday, May 17, 2008
String extension methods in ASP.Net Ajax

In an earlier post, I showed you how you could add a trim() method to the String class in Javascript.  Well, as I found out late last week, if you are using the ASP.Net Ajax framework, they have already done this work for you (as well as a few more methods).  Here are the extension methods for the String class that are provided to you:

Method Description
endsWith() Test to see if the string ends with a particular string
format() Similar to .Net's String.Format(), it replaces a set of tokens with some replacement values
localeFormat() Similar to format(), but it uses the current culture to format dates and numbers
startsWith() Test to see if the string begins with a particular string
trim() Strips both leading and trailing whitespace from the string
trimEnd() Strips whitespace from the end of the string
trimStart() Strips leading whitespace from the string

One other nice thing it provides is a StringBuilder class similar to .Net's System.Text.StringBuilder class.  This is especially nice when creating big chunks of HTML to throw in an innerHTML property.

<input type="button" name="btn1" value="Click Me!" onclick="javascript:changeText();"><br />
<span id="myText"></span>
<script type="text/javascript">

function changeText() {
var sb = new Sys.StringBuilder(); // thank you, ASP.Net Ajax!
sb.append('<h1>How cool is this?</h1>');
sb.append('<br />');
sb.append('You just clicked my button. ');
sb.append('Now we will change some text');

$get('myText').innerHTML = sb.toString();
}

</script>

Kick it on DotNetKicks.com
Saturday, May 17, 2008 10:32:30 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  Ajax | ASP.Net | Javascript

 Wednesday, April 16, 2008
It's funny because it's true!

I just received this from Scott Hanselman's twitter feed (where he is attending the Microsoft MVP conference):

twitter: shanselman: "The UpdatePanel is like crack." - #mvp08

:-)


Kick it on DotNetKicks.com
Wednesday, April 16, 2008 12:37:53 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | ASP.Net | Conferences | Humor

 Thursday, April 10, 2008
Starting out with ASP.Net Ajax and the Ajax Control Toolkit

So only javascript gurus can make slick Ajax-enabled web pages, right? Wrong! Want to know the dirty little secret?  It's actually really easy!

If you are not using Ajax already on your ASP.Net pages, here's a great place to start.  It's always bothered me how on something as simple as paging and sorting on a GridView caused a full postback. Wrap that sucker in an UpdatePanel and you’ve instantly Ajax-enabled your page! By including the declaration ChildrenAsTriggers="true" (or not declaring it at all – it’s the default option), any postback event triggered in the UpdatePanel will automatically cause the page to partially re-render its contents. That’s it! No javascript needed. Well, actually there’s a ton of javascript involved – just none of it written by you. ;-)

First off, you need a couple of resources to get started. If you are using the 3.5 version of the framework, ASP.Net Ajax is already included by default. If you are using .Net 2.0, you will need to download the ASP.Net Ajax Extensions 1.0 (could they make it *any* more confusing?).

I am using the Ajax Control Toolkit to perform the animations during the partial post-back. The Ajax Control Toolkit has a nice set of tools to use to help you build rich web UIs, and as Clark Howard would say, "Hey, it's free!!!!" In the example below, I am using the UpdatePanelAnimationExtender to declaratively set a FadeOut animation to occur on the div container surrounding the UpdatePanel as the page posts back, and a FadeIn animation as it re-renders.

OK, so I lied. I am actually using a little javascript to dynamically show a spinning loading image centered on the grid during the postback.  But, again, the ASP.Net Ajax library to the rescue!  It makes our life a lot easier by providing all sorts of nice javascript shortcuts that are cross-browser compatible (like the Sys.UI.DomElement.getBounds() call I’m using).

Oh, you need to check out this site that will generate a custom loading image for you. Make sure you select a transparent background when you build your image.

Here is the code:

<!-- loading image is hidden by default -->
<img id="imgLoading" src="images/ajax-loader.gif" alt="Loading..." width="30" height="30"
style="display: none;" />
<div id="container">
<asp:UpdatePanel ID="updPnl" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="gvw" runat="server" CssClass="grid"
HeaderStyle-CssClass="header" AutoGenerateColumns="false" RowStyle-CssClass="odd"
AllowPaging="true" AllowSorting="true" AlternatingRowStyle-CssClass="even">
<Columns>
<asp:BoundField SortExpression="ID" HeaderText="ID" DataField="ID" />
<asp:BoundField SortExpression="Name" HeaderText="Name" DataField="Name" />
<asp:BoundField SortExpression="BirthDate"
HeaderText="Date Of Birth" DataField="BirthDate" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<ajaxToolkit:UpdatePanelAnimationExtender ID="animator" runat="server" TargetControlID="updPnl">
<Animations>
<OnUpdating>
<Sequence>
<!-- shows the loading image in the center of our grid -->
<ScriptAction Script="showInProcessImage($get('imgLoading'), $get('container'));" />
<Parallel duration=".10" Fps="30">
<FadeOut AnimationTarget="container" minimumOpacity="0" />
</Parallel>
</Sequence>
</OnUpdating>
<OnUpdated>
<Sequence>
<Parallel duration=".25" Fps="30">
<FadeIn AnimationTarget="container" minimumOpacity="0" />
</Parallel>
<!-- hides the loading image -->
<ScriptAction Script="hideInProcessImage($get('imgLoading'));" />
</Sequence>
</OnUpdated>
</Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>

And the javascript:

<script language="javascript" type="text/javascript">

// show the image in the center of the container
function showInProcessImage(img, container) {
// get the bounds of both the container and the image
var containerBounds = Sys.UI.DomElement.getBounds(container);
var imgBounds = Sys.UI.DomElement.getBounds(img);

// figure out where to position the element (the center of the container)
var x = containerBounds.x +
Math.round(containerBounds.width / 2) - Math.round(imgBounds.width / 2);
var y = containerBounds.y +
Math.round(containerBounds.height / 2) - Math.round(imgBounds.height / 2);

// set the position of the in progress image
Sys.UI.DomElement.setLocation(img, x, y);

// finally un-hide it
img.style.display = '';
}

// hide the image
function hideInProcessImage(img) {
img.style.display = 'none';
}

</script>

I've left out the details of actually handling the paging and sorting events on the GridView.  I assume you are doing that already (or know how to do it).

One more thing to keep in mind - even though you are partially rendering the screen, you are still hitting the server (and your code-behind page).  On your partial post-backs, don't perform any extra work in the code-behind that's not going to be rendered in the update panel (e.g. hitting the DB, populating drop-down lists, setting headings, etc.). And don’t be fooled into thinking that Ajax-enabled web apps take a significant burden off the server.  If they are designed to be too "chatty", they can even make things worse!


Kick it on DotNetKicks.com
Thursday, April 10, 2008 9:42:23 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | Ajax Control Toolkit | ASP.Net

 Wednesday, March 26, 2008
Changing a control's CSS class name during validation

So I'm converting an ASP.Net prototype that was written entirely in VB Script (don't ask) to C#.  As part of the conversion, I am putting in ASP.Net validation controls on all the input fields in the application.  I was showing off my progress to the graphics designer, and he pointed out that he wanted to dynamically change the CSS class on the input field control that was being validated if it failed validation.  Hmm, I can set the CssClass attribute on the validation control, but I couldn't find anywhere to automatically change the CSS class name on the actual control being validated.

I *could* write custom validators for each input control and change the class name in the javascript validation function, but that seemed like too much work.  So I thought to myself, surely there is some way to add an event listener to the DOM on the validation control to see if it changed it's display attribute.  After some researching, I got it to work.

<head runat="server">
    <title>Test Page</title>
    <style type="text/css">
      .error
      {
        border: solid 1px red;
        background-color: Yellow;
      }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <asp:TextBox ID="txtBox" runat="server" />
            <asp:RequiredFieldValidator ID="reqField" runat="server" ControlToValidate="txtBox"
                Display="Dynamic" EnableClientScript="true" ErrorMessage="* Required"
SetFocusOnError="true" />
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        </div>
        <script type="text/javascript" language="javascript">
    function pageLoad() {
        $addHandlers($get('<%= this.reqField.ClientID %>'),
                     { 'DOMAttrModified' : changeTextBoxClass,
'propertychange' : changeTextBoxClass });
    }
    function changeTextBoxClass(eventName) {
        $get('<%= this.txtBox.ClientID %>').className =
            $get('<%= this.reqField.ClientID %>').style.display != 'none' ? 'error' : '';
    }
        </script>
    </form>
</body>
</html>

DOMAttrModified is not supported in IE (shocking!!!) - onpropertychange is the IE equivalent.  Basically, whenever the ASP.Net validators fire and change the "display" attribute on their enclosing <span> tags, I added an event handler that will dynamically set the CSS class on the corresponding input control.  Notice in the example above that I'm using the ASP.Net Ajax library to make my life easier.

Before validation:

image

 

And after the "Submit" button is clicked:

image


Kick it on DotNetKicks.com
Wednesday, March 26, 2008 9:14:38 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | ASP.Net