This post shows how to add dynamic username availability lookup to an ASP.NET MVC view, using jQuery and C#. There are three parts to the solution: the html form, jQuery function, and the controller.
Html form
This part is pretty simple: a textbox for the username field with an onchange event, a div to hold the lookup results, and a lookup button.
<h3>Username</h3>
<%= Html.TextBox("Username", "", new { @onchange = "CheckAvailability()" })%>
<div style="display:inline;" id="usernamelookupresult"></div><br/>
<input type="button" value="Check Availability" onclick="CheckAvailability()" />
</code>
jQuery Username Lookup
This is where the magic happens. Well, nothing really magical, just a jQuery call to a controller, passing in the username value. In the example below, the function processing the result looks for a 0 to indicate the username is available. You can modify that to be whatever you want.
function CheckAvailability() {
$.post("/Home/CheckAvailability",
{ Username: $("#Username").val()},
function(data) {
var myObject = eval('(' + data + ')');
var newid = myObject;
if (newid == 0) {
$("#usernamelookupresult").html("<font color='green'>Available :-D</font>")
}
else {
$("#usernamelookupresult").html("<font color='red'>Taken :-(</font>")
}
});
}
Controller
This is where your business logic lives, and is where the lookup occurs. For this exercise, we are keeping it simple, but you can see where to add your database lookup.
public ActionResult CheckAvailability(string Username)
{
int Taken = 0;
// This is where you add your database lookup
if (Username == "username")
{
Taken = 1;
}
return Json(Taken);
}
Below is a quick clip to show the code from the downloadable sample in action:
