asp.net mvc: Is that username available?

Digg it! del.icio.us  |  kick it on DotNetKicks.com  |  Stay updated with rss  |  Add to Google


I been using prototype for few of my project lately, however, I been hearing some wonderful things about jquery so decided that it is the right time to give it a short. Here is what I tried to implement with jquery on asp.net mvc. I decided to add the ability to automatically check whether the username given by the user on the registration page is already taken or is available. For this I added a new action on the account controller named “check”. This action returns a ContentResult containing the text to display. Code follows:

public ContentResult Check(string id)
{
if (Provider.GetUser(id, false) == null )
return Content(”");

return Content(”The username is already taken.”);
}

this function takes the username entered by the user as its parameter and checks if the username is available or not. If available, it returns nothing and if the name is already taken it returns the error message. After getting this done, now we will have a look at the changes made to the registration page’s view.

The main change other than adding the jquery magic, is to add a span where to display the output from our check action. We will place it just after the text field for entering username. Modified table row of the username field is shown below.

<tr>
<td>Username:</td>
<td><%= Html.TextBox(”username”) %>
<span id=”isUsernameAvailableResult”></span>
</td>
</tr>

after this, we will add the following script to the view. Note: I have included the jquery.js in this snippet, in real world you would probably have it included inside your master page.

<script src=”/content/js/jquery-min.js” type=”text/javascript”></script>
<script language=”javascript” type=”text/javascript”>
$(document).ready(function(){
$(”#username”).blur(function(){
$(”#isUsernameAvailableResult”).load( “check/” + escape(document.getElementById(”username”).value) + “.aspx”);
});
});
</script>

Here we first add the anonymous function containing the actual code which does the ajax call to the blur event of the username text box. We do this inside the jquery special document.ready event)

The code just selects the span to contain the result and load the output of the ajax call into it. Here
the request url is “/account/check/[user entered name here].aspx”. Note: I use a modified routing rule in which the url always ends in “.aspx”. This is to make it work it on iis 6 also without any big changes.

jquery is a great tool to have, and with the introduction of asp.net mvc, integrating jquery with asp.net is easyer than ever. Enjoy,


If you liked this post, please subscribe to this blog or kick this story on DotNetKicks.com .

Tags: ,

You may want to take a look at these posts

You can leave a response, or trackback from your own site.

Leave a Reply


© 2008 By Nirandas, All rights reserved.