Handling Text Changed Event In ASP.NET MVC 3 With JQuery

In my quest of learning MVC I came across many problems and here is one of them. I was trying to fire an event whenever a text changed event occurred. I am using JQuery to handle the text changed event but eventually the text changed event doesn’t seems to be working in MVC as it is working for a text box changed event in web forms. The solution I found seems to be working fine for me as I don’t want to fire an event on every key press.

To get started fire Visual Studio and create a new MVC 3 application with RAZOR view engine. I have build a simple contact manager application which allows the user to create a new contact, edit and delete existing contacts. While creating a new contact, what I want is when the user enters the e-mail address of the contact I want to make an AJAX call, which then call the method in the controller and return the HtmlString which will then show the Gravatar on the webpage.

Here is the default view of the index view. I will ask the user to enter some very basic information like name, address, email and phone.

Adding a contact page

Now, when the user enters the email address of the contact and press TAB key to move to another field or just click somewhere else on the page, the focus on the text field will be changed and the controller function then returns HtmlString to show the Gravatar image.

Here is the markup of the Create View (Create.cshtml):

@model TextChangedMVC.Models.Contacts
@{
    ViewBag.Title = "Create";
}
<h2>
    Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Contacts</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            <div id="Gravatar">
            </div>
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone)
            @Html.ValidationMessageFor(model => model.Phone)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Check the highlighted code in the above markup where I have a DIV called Gravatar. This is where I will display the Gravatar of the person. Remember, when the user enters the email address we need to make sure that the Gravatar of the person displays without being an obstruction to the user, so an AJAX request to the controller will help in achieving this.

Below is the Jquery which will call the controller method called Avatar which accepts email as a parameter of string type.

<script type="text/javascript">
    $('#Email').change(function () {
        $('#Gravatar').html('');
        var selection = $('#Email').val();
        if (selection.length > 0) {
            $.post("/Home/Avatar", { email: selection },
        function (data) {
            $('#Gravatar').html(data)
        })
        }
    });
</script>

The above script is simple and here I am calling the controller’s Avatar method which returns an HtmlString. At line 6, we are making a request and calling the controller’s method. At line 8, the data (which is a HTML) returned will be set on the DIV called Gravatar (the placeholder for the Gravatar image).

Gravatar being rendered on web page

The controller method Avatar is as follows:

public HtmlString Avatar(string email)
{
      return Gravatar.GetHtml(email, defaultImage: "http://midnightprogrammer.net/pics/default.gif");
}

Gravatar is a method is a part of the Microsoft Web Helpers. You can use web helpers by downloading it via NuGet. Check it out here if you miss my blog post on how to use Microsoft Web Helpers in MVC.

Related Post:

comments powered by Disqus