Using ASP.NET MVC and Ajax to check names availability.
This article demonstrates how to use ASP.NET MVC Ajax and JQuery to create a MVC User Control that checks the availability of a name. For example you may want to create a URL route that includes project names as parameters and you want to make sure those names are unique. The control will look like this:
Key Validator
Using jQuery and ASP.NET MVC Ajax we can call the view’s controller to check the availability of the name:
Validating project name.
Project name available.
Project name already in use.
Open Visual Studio 2008 and create a new ASP.NET MVC 1.0 project, now we need to create the KeyValidatorController class inside the Controllers folder:
KeyValidatorController.cs
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.Mvc;
6: using System.Web.Mvc.Ajax;
7: using System.Threading;
8:
9: namespace CheckKeyName.Controllers
10: {
11: public class KeyValidatorController : Controller
12: {
13: //
14: // GET: /KeyValidator/Check
15:
16: public ActionResult Check(string projectName)
17: {
18: Thread.Sleep(5000);
19:
20: if (!String.Equals(projectName, "superProject", StringComparison.InvariantCultureIgnoreCase))
21: return Content("Available");
22:
23: return Content("Already in use.");
24: }
25: }
26: }
As you can see in line 18, we are using the Thread.Sleep(5000) method to simulate a 5 seconds delay in our application while the information is retrieved.
Line 20 compares the project name with a hardcoded string and in line 23 we return the text result to the view, pretty simple right? (In a real application we would replace lines 20 and 21 by the actual code to access a names catalog and perform the validation).
In lines 21 and 23 we are using the Content accion result to return a string to the View.
Now lets create the KeyValidator View by adding a new MVC User Control inside the Shared folder of the Views:
KeyValidator.ascx
1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
2:
3: <script language="javascript">
4:
5: function checking() {
6: $("#statusMsg").html('');
7: $("#checkButton").hide();
8: }
9:
10: function checked() {
11: $("#checkButton").show();
12:
13: if ($("#statusMsg").html() != "Available")
14: $("#statusMsg").addClass("error");
15: else
16: $("#statusMsg").removeClass("error");
17: }
18:
19: function previewUrl(e) {
20: $("#statusMsg").html('');
21: $("#projectUrl").html(e.value);
22:
23: }
24:
25: </script>
26:
27: <%using (Ajax.BeginForm("Check", "KeyValidator", new AjaxOptions {
28: LoadingElementId = "working",
29: OnBegin = "checking",
30: UpdateTargetId = "statusMsg",
31: OnSuccess = "checked"
32:
33: } )) { %>
34:
35: <%= Html.TextBox("projectName", null, new { onkeyup = "javascript:previewUrl(this);", style = "float:left;" })%>
36: <input id="checkButton" type="submit" value="check"/>
37: <img id="working" alt="working" src="../../Content/Images/working.gif" style="display:none;" />
38: <div id="statusMsg" style="display:inline"></div>
39: <div class="clear"></div>
40: http://server/project/<div id="projectUrl" style="display:inline"></div>
41: <% } %>
In this View we are using the Ajax.BeginForm helper to create an Ajax form that will post the data to the Check action of the KeyValidator controller. In line 27 we are setting the following Ajax Form properties:
-
LoadingElementId = "working"
The ID of the Html element that will be displayed while the request is been completed. In this case we are displaying a progress bar. Note the style="display:none;" attribute in line 37 to hide the image, the MVC Ajax helper will automatically display the image when necessary. -
OnBegin = "checking"
The name of the JavaScript function that will be called when the user clicks on the Check button, this function clears any status message and hides the Check button. -
UpdateTargetId = "statusMsg"
The ID of the Html element that will be filled with the controller text result. -
OnSuccess = "checked"
The name of the JavaScript function that will be called after completing the validation process, in this function we check the controller response and set the style of the text. -
In line 35 we are using another helper to render a TextBox and we show how to hook the onKeyUp java script event with our previewUrl method to update the preview URL text.
Finally lets modify our Home page to add our user control, open the Index view and add the code to render the partial view (Line 12):
Index.aspx
1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
2:
3: <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
4: Home Page
5: </asp:Content>
6:
7: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
8: <h2><%= Html.Encode(ViewData["Message"]) %></h2>
9: <p>
10: To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
11: </p>
12: <% Html.RenderPartial("KeyValidator"); %>
13: </asp:Content>
If you run your application, enter different project names and see how the URL preview is updated as you type in, when you press the Check button the progress bar will be displayed and a few seconds later the reponse will be presented to the user.
Comments
13 Responses to “Using ASP.NET MVC and Ajax to check names availability.”Trackbacks
Check out what others are saying...-
[...] to VoteUsing ASP.NET MVC and Ajax to Check Name Availability (12/16/2009)Wednesday, December 16, 2009 from forerunnerg34.wordpress.comThis article demonstrates how to use [...]
-
[...] View Article Rating 3.00 out of 5 [?] Tags: Asp.Net, MVC Share this post! [...]
-
[...] Using ASP.NET MVC and Ajax to check names availability. October 2009 12 comments 35.534906 139.556122 LikeBe the first to like this post. [...]
nice!
Nice!
Thanks!
this is a main feature for a web application and everybody is doing it by their own way,i like the way you did it.
thanks
Great post! MVC has more support the javascipt!
Very good and excellent work and Article . Can we restrict the number of typed characters in the text area with this jquery plugin ??
Thanks everybody for your comments!,
@Hamid: Yes, you could modify the “previewUrl” method to check the number of characters in the client side, or you can try using ASP.NET MVC Validators.
I like this post very much, i will search so many pages for using mvc and ajax to checking names availability.
This post is very useful for me, i will use it on my site http://ignou-student.blogspot.com
What is a Web Form?…Sweet post man.
BTW, people already asking MVC questions on the interviews… going in much of details including namespace and class names questions. Check it here: http://interviewpattern.com/post/ASPNET-MVC-Interview-questions.aspx
bhangar