Validate Username Using jQuery AJAX, JSON, and ASP.NET Web Method

by aherrick 11. February 2009 08:59

As of late, I have been working on using AJAX in my code to call ASP.NET Web Methods and Web Services.  There are a couple of different ways to accomplish this, including using the ASP.NET Script Manager, (see here) however there is a lot of overhead with instancing the Script Manager that is not always necessary.

The method below using the jQuery.AJAX call which even includes built in error checking functionality.  In this example, I am going to call a Web Method in the code behind that will validate the username text field input and return a boolean regarding if the username is valid. 

In a normal production environment, in your Web Method you would want to hit a database to validate the input, however for this demo I am going to simulate that.  If the username entered equals “testuser”, the method will return false, otherwise return true resulting in a valid username.

First we are going to add our html to the page:

<div>
    Username:
    <input id="tbUsername" type="text" />
    <span id="valid"></span>
</div>
<!-- preload -->
<div style="display: none">
    <img src="images/available.gif" alt="available" />
    <img src="images/taken.gif" alt="taken" />
    <img src="images/waiting.gif" alt="waiting" />
</div>

Here I am creating a simple html textbox and span tag.  We will use the Javascript code to change the html of the span tag.  It is a place holder for now.  Also I add an image preload div using CSS so the necessary images are loaded at runtime.  display: none ensures the images will not be visible on the screen.  This ensures a smooth effect when hiding/showing the images dynamically.

Next we are going to create our simple Web Method in the code behind.

using System.Web.Services;
[WebMethod]
public static bool IsUserAvailable(string username)
{
    // simulating db call here
    if ((!username.Contains(" ") || !username.Contains("")) && username != "testuser")
        return true;
    else
        return false;
}
 
All we are doing is creating a simple method to return if the user is valid. 

Now lets take a look at the Javascript required to make this all happen.

<script type="text/javascript" src="scripts/jquery-1.2.6.min.js"></script>
 
<script type="text/javascript">
    $(document).ready(function() {
        $("#tbUsername").blur(function(event) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/IsUserAvailable",
                data: "{'username': '" + $('#tbUsername').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $('#valid').html("<img src='images/waiting.gif' alt='Checking username!'>");                       
                    var delay = function() {
                        AjaxSucceeded(msg);
                    };
 
                    setTimeout(delay, 2000);
                },
                error: AjaxFailed
            });
        });
    });
    function AjaxSucceeded(result) {
        if (result.d == true)
            $('#valid').html("<img src='images/available.gif' alt='Username available!'>");
        else
            $('#valid').html("<img src='images/taken.gif' alt='Username taken!'>");
    }
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }    
</script>

Here is where the magic happens.  Using jQuery we are getting a reference to tbUsername and adding blur event.  Adding the event through jQuery leads to better cross browser compatibility. 

Using jQuery.ajax we define our variables:

  1. type: “POST” – this ensures we are posting to the server
  2. url: “Default.aspx/IsUserAvailable” – sets the page and method we are calling
  3. contentType: “application/json; charset=utf-8”
  4. dataType: “json” – using JSON as the data type, this could be XML, etc.
  5. success: – here we are creating a function to determine what to do with the Response from the server i fit was successful
  6. error: – allows us to define an error method if something goes wrong.

Here is what our POST/RESPONSE looks like in debug mode with Firebug

POST:

usernamePost

You can see what we are sending, username defines the argument name and test is the value entered into the textbox.

RESPONSE:

usernameResponce

After successfully validating the username in the Web Method, it sends back a true.  For more information on what the d value is, give this blog post esconia a read.

Finally if the response was true, we set the html of the span to the success image, otherwise set it to taken!

I hope this code is a jump-off point to get you started with jQuery AJAX, JSON, and ASP.NET and gives you a glimpse at how powerful it can really be!  Posted below is the code in its entirely, please test it out and let me know what you think!

jQueryAJAXValidateUsernameWebMethod.zip (39.30 kb)

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ASP.NET 2.0 SubSonic Project Template With SQL Server 2005 Northwind DB

by aherrick 29. December 2008 01:39

I created this template mostly for myself so that when I am creating web demos/test projects I have a wired up SubSonic project ready to go.  Hopefully it will be useful for someone interested in getting started with SubSonic.  Setup is currently running SubSonic 2.0.3.  I have found this to be the most stable version to date.  I will be putting up a version 2.1 (and hopefully 3.0) template soon.

Rob Conery, SubSonic creator, has some great videos on getting started as well.  Check it out at http://subsonicproject.com

This solution is completely wired using ASP.NET 2.0 and SQL Server 2005.  I broke the solution up to into two projects (DAL and WEB).  This way seems to work well and allows for abstraction.  In order to run, make sure you are running the Northwind database (just run ins). 

Good luck and let me know if you have problems running the solution.

SubSonicSMall

SubSonicNorthwindDBTemplate.zip (869.28 kb)
InstallNorthwind.zip (274.19 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ASP.NET Programmatically Control MasterPage and CSS

by aherrick 22. December 2008 07:14

Working on a project I need the ability to programmatically change the web application's associated master page (and associated CSS).  Most of the pages in the application were content pages (derived from the content page) however some were just static pages.  Since there was no MasterPage assoicated with these static pages, dynamically assigning the CSS was the next best option.

I created a BasePage for ALL pages in the application to derive from. 

For the ContentPages (pages that point to a MasterPage) I created a method in the BasePage to assign the necessary master page.  This method is called in the Page_PreInit method of the content page.  See below.

        protected void Page_PreInit(object sender, EventArgs e)
        {
            // set master page
            this.SetMasterPage();
        }

SetMasterPage is a simple method to dynmically change the MasterPage...

        public void SetMasterPage()
        {
            // change master page

            // will return random number between 1-3...      
            int masterPage = RandomNumber(1, 4);

            string fullMaster = ResolveUrl(string.Format("~/Site{0}.master", masterPage));
            this.MasterPageFile = fullMaster;
        }

Dynamically set the CSS on the static pages in a similar matter.  In the code behind of the specific page, , call SetCSS in the Page_Init method.  Dynamically setting the CSS is very easy too...

        public void SetCSS()
        {
            // set CSS

            // ALL CSS has to be set programatically... 
            HtmlLink css = new HtmlLink();
            int cssNum = RandomNumber(1, 3);

            css.Href = ResolveUrl(string.Format("~/StyleSheet{0}.css", cssNum));
            css.Attributes["rel"] = "stylesheet";
            css.Attributes["type"] = "text/css";
            css.Attributes["media"] = "all";
            Page.Header.Controls.Add(css);
        }

Really that's all there is to it.  This code can be tweaked to suit your needs.  This gives a lot more flexibility than simply dynamically changing your CSS file.

Attached is the code

ControlMasterPagesProgramatically.zip (34.59 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# Directory List Application

by aherrick 9. December 2008 11:11

I am releasing this application I created to help me organize my music collection.  It takes multiple paths and combines ever directory under each path into a single txt/csv file sorted alphabetically.  I had a little fun with some of the validation and colors to make it work a little more smoothly. 

dl

Usage:

  1. Select paths using Add
  2. Select output format (txt or csv)
  3. List is generated to same directory .exe is located

Attached is the .exe and full source code.  It is free for distribution and please feel free to tweak to your needs!

If I tweak this in the future I will post the updated code, consider this V1.0

Enjoy!

DirectoryListV1.0-FullSRC.zip (73.37 kb)
DirectoryListV1.0EXE.zip (12.18 kb)

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

ASP.NET Control HTML Elements/Tags Programmatically

by aherrick 3. December 2008 06:34

I was working on a project and was looking for more control over the elements I was creating in the HTML.  More specifically, I had a MasterPage setup and I wanted all pages to have the same background image throughout the site.

Simple.  Add a runat=server to your markup.  See below. 

<div id="bgimg" runat="server">
</div>

You now have control of this element from the code-behind.

To add a background image to the div, you could do something like this:

bgimg.Style[HtmlTextWriterStyle.BackgroundImage] = ResolveUrl("~/images/bodyback.jpg");

The only thing to realize is what your generated markup is.  Asp.Net will auto-generate this tag to prevent naming collisions.  Just look out for it if you are trying to style the element with CSS or call it using javascript.

<div id="ctl00_bgimg" style="background-image:url(/HRR/images/bodyback.jpg);">
</div>

Enjoy!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

IIS 6.0 serving unknown file extensions?

by aherrick 17. November 2008 10:25

We were working on a web project that was served on IIS 6.  In the code, we were creating our own extensions (.BUYER, .PACK., .ITEM) for example.  The problem occurred when these files became unavailable for download when running the site through IIS. 

"Internet Explorer cannot download X"

iis6 cannot download

The solution was simple. 

  1. Open IIS, right click on the local computer name and select properties.

iis 6 properties

    2.   Select "MIME Types"

    3.   Select "NEW"  

    4.   Input the extension and application/octet-stream for MIME Type.  If you want to allow ALL extensions, add an asterick (*).

iis6 mime type

That simple!  Good luck :)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# Twitter Extension

by aherrick 29. September 2008 15:06

I was looking for an easy solution to add Twitter to my blog, and decide to write a class extension to fit my needs.  With input from Fence Row Productions I came up with a class to easily grab your most recent tweet and display it on your blog.  The code will parse Twitter API to display your most recent Tweet.


Check out how I am currently using it.

Added two ASP.NET label controls "lblTweet" and "lblTweetInfo." Also added an image control "imgTweet."

Here is my current code behind file for my MasterPage.  The class constructor is your Twitter login name (twitter.com/you)

   imgTweet.ImageUrl = "~/pics/twitter_bird_32.png";

   Twitter t = new Twitter("andrew_herrick");
   this.lblTweet.Text = t.TweetStatus;
   this.lblTweetInfo.Text = 
        string.Format("<a href='{0}' target='NEW'>{1}</a> from {2}.", 
        t.TweetURL, t.TweetDateDiff, t.TweetSource);
 

Attached is the complete class. Let me know how it goes and enjoy!

Twitter.cs (4.65 kb)

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# Get Date Difference

by aherrick 5. September 2008 04:21

I was working on my Twitter extension to display my most recent tweet and I wanted to display how long ago I tweeted.  I was able to acquire some code which I tweaked a bit to fit my needs.  Check it out!

This method accepts two dates that you want to compare.  For example: In my case, date1 is "DateTime.Now" and date2 is the Tweet date (whenever my most recent tweet was).  I will have a full post on the twitter extension you see above soon!

Take a look at the code below!

    private string GetDifferenceDate(DateTime date1, DateTime date2)
    {
        if (DateTime.Compare(date1, date2) >= 0)
        {
            TimeSpan ts = date1.Subtract(date2);
            // if more than 1 day ago
            if (ts.Days > 0)
                return string.Format("{0} days, {1} hours, {2} minutes", 
                ts.Days, ts.Hours, ts.Minutes);
            else
                return string.Format("{0} hours, {1} minutes", ts.Hours, ts.Minutes);

        }
        else
            return "Not valid";
    }

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Pure CSS Rollover Popup Effect

by aherrick 2. September 2008 11:25

The other day we had a request from a client to provide a rollover effect to display data.  They only wanted it to display when a text area was hovered.  One of my coworkers and I came up with a solution that fit our needs.  I tweaked it a bit from using a DIV to using links and span tags. This makes it more flexible. Here is what I came up with. This solution that is cross-browser compatible.

HTML

CSS

First I start by setting up the link.  The point of setting the z-index is to make sure the "popup" effect floats above all other elements on the page. 

I am made two classes, rollover for the link and tooltip for the text to show.  This will distinguish between other a link and span tag attributes on the page. 

Initially the span tooltip is set to not display.  The final part of the CSS is what the span tag looks like when the link is hovered.  This is where there is a lot of flexibilty on how you want your tooltip to look.  I positioned the tooltip absolute based on the relative position of the link. 

I played with the colors and padding to come up with something I liked.  This can be changed to fit your sites needs of course.

Here is the full code for your enjoyment!

PureCSSRolloverPopupEffect.zip (2.28 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Ajax Control Toolkit Autocomplete Extender Weird Issue

by aherrick 20. August 2008 05:08

Okay I was working on testing the Autocomplete Extender on a site I am working on.  I noticed something interesting when testing the search functionality.  Take a look at what was going on:

Here is what the control source looked like:

As you can see, the SKU codes I was looking for started with "TEST". But if a bunch of junk text was included before the actual SKU, it would stay with it in the dropdown list.  I finally found the solution by removing the "DelimiterCharacters" from the control.  I hope this works for you!

On an unrelated note I accepted a full time position at Blue Horseshoe Solutions today, I am thrilled.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,



Powered by BlogEngine.NET 1.4.0.0
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!

Categories

None

Recent comments

Comment RSS

Page List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008