TextBox Watermark using HTML5 and jQuery

A ‘TextBox Watermark’ is an UI effect that is often employed in space constrained scenarios where putting in a label next to a text box explaining the purpose of the textbox is not possible. In such scenarios, the TextBox has a watermark that stays on till a user starts typing. For example the WordPress.com home page

wordpress

Here when we start typing on the Username or the Password textbox, the text vanishes allowing you to put in your username and password

wordpress-login

Apart from the above use case, it is often used to show sample data or expected formatting. This effect has become so popular that it is now supported in HTML5 <input> elements through an attribute called ‘placeholder’. But like all things, not all browsers support HTML5 yet. The following html

textbox-watermark

gives us the following out put on IE9, Firefox 12 and Chrome 19.

ie9-watermark-nosupport

As we can see above, IE9 does not support this effect.

To get the same effect across all browsers we will develop a small jQuery plugin that will take the placeholder value provided and applies the watermark effect across all browsers.
Creating the Plugin
We will go step by step on how to create the jQuery Plugin.

Step 1: Basic Syntax

jQuery plugins are JavaScript function properties added to the jQuery.fn object from the jQuery library. The syntax for it is as follows:

jQuery.fn.inputWatermark = function() 
{
    // The plugin related methods here  
};

As we see above, inputWatermark is the name of our plugin. You can replace it with a name of your choice for the plugin.

Step 2: Using the $ symbol

Now we can wrap the above in an immediately invoked function expression (IIFE) so that it maps to the $ sign and it can’t be overwritten by another library in scope of its execution. So our boilerplate code becomes


(function ($) 
{
    $.fn.extend({
        inputWatermark: function() {  
        // The plugin related methods here  
      }
    });
})(jQuery);


Step 3: Maintaining Chainability

We want our plugin to be applicable to multiple <input> elements because we can have multiple text boxes to which the watermark needs to be applied. We also want to be able to pass on the ‘inputWatermark’ along to the next method in the chain. To do this, our plugin must return the ‘this’ keyword. So our shell code is modified to the following


(function ($) {
    $.fn.extend({
        inputWatermark: function () {
            var options = datasource;
            return this.each(function () {
                // plugin code
            });
        }
    });
})(jQuery);

Step 4: Setting up the Code
The logic for the watermark behavior is simple.
1. If no text have been provided by the user, show the watermark text
2. When user enters the input box, remove the watermark
3. When the user exits the input box if they haven’t added any text, put the watermark back.

To do the above, we handle the blur and focus events of the input element. On plugin initiation, we check if value provided is not empty, if it is, we add the watermark. The code is as follows


(function ($) {
    $.fn.extend({
        inputWatermark: function () {
            return this.each(function () {
                // retrieve the value of the ‘placeholder’ attribute
                var watermarkText = $(this).attr('placeholder');
                var $this = $(this);
                if ($this.val() === '') {
                    $this.val(watermarkText);
                    // give the watermark a translucent look
                    $this.css({ 'opacity': '0.65' });
                }



                $this.blur(function () {
                    if ($this.val() === '') {
                        // If the text is empty put the watermark
                        // back

                        $this.val(watermarkText);
                        // give the watermark a translucent look
                        $this.css({ 'opacity': '0.65' });
                    }
                });



                $this.focus(function () {
                    if ($this.val() === watermarkText) {
                        $this.val('');
                        $this.css({ 'opacity': '1.0' });
                    }
                });
            });
        }
    });

})(jQuery);

We update our HTML to the following


<!DOCTYPE html>
<html>
<head>

    <title>TextBox Water Marking</title>
    <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <script src="Scripts/input-watermark.js" type="text/javascript"></script>
</head>


<body>
    <input id="input1" placeholder="Placeholder here..." />
    <input id="input2" placeholder="2nd Placeholder" value="This is actual Text" />
    <script type="text/javascript">

        $(document).ready(function () {
            $(':input').inputWatermark();
        });

    </script>

</body>
</html>

As seen above we are assigning the plugin using the type selector. This assigns the plugin to all input boxes. The beauty is that we use HTML5 style markup and the same attribute (placeholder).

We could assign the plugin to individual input elements too by using the id selector

$('#input1').inputWatermark();
or
$('#input2').inputWatermark();

Finally our code in action looks as follows

ie9-watermark-fix


See a Live Demo

Using the ‘Remote’ Attribute for Async Validation in ASP.NET MVC

Validation is an integral part of any input process in any computer software. As the saying goes ‘never trust anything the user gives you’. On the web, there are various ways of validating user input, some happen on the web-browser itself, some happen on the server after a user submits a form of data.

ASP.NET MVC 3.5 onwards supports various Data Annotation attributes that you can decorate your View Model with. The Data Annotations combined with Unobtrusive Client Side Validation using jQuery.Validation framework takes care of most common validation scenarios. However there are times when we want one special feature that is difficult to achieve using either pure client side or pure server side validation functionality built in. For such cases, ASP.NET MVC supports an attribute called ‘Remote’. The ‘Remote’ attribute takes in a Controller Action name and wires up the required JavaScript to do an Async Get operation on change of value in the UI.

Today we will see how we can use the ‘Remote’ attribute to enhance the default Registration page that comes with ASP.NET MVC4 Internet template. You can adapt it for validating any text on the server side.

Use Case for Async Server-Side Validation

Let’s start off by creating an ASP.NET MVC application (I am using MVC 4RC here, but you could use MVC3 with .NET 3.5 SP1 too).

Step 1: Select the ‘Internet Application’ Template. This adds the AccountController and related Account related Views.

internet-application-template

Step 2: Update the web.config’s connection string setting to point to the correct database and update the Database name. Also notice the two attribute ClientValidationEnabled and UnobstrusiveJavaScriptEnabled. These two attributes help wire up the DataAnnotations specified on the Model with the validations performed by the jQuery.Validation framework.

web-config-changes

Step 3: Run the Application and click on Register on the top right corner.

register-link

Step 4: Register using valid registration details


first-user-registration

Step 5: Once registered, log out and go to the Registration page again. Provide the same username as you provided earlier, put in all other details correctly and hit Submit. System comes back with an error saying User already exists.

second-user-registration-postback

The User in this case was warned of an issue after they hit Submit. It would be really nice if the User were warned of this issue as soon as they entered the User name. How can the User Name be validated? It is definitely not a client side validation as the list of existing users is only available on the server. For these kinds of scenarios we use the ‘Remote’ attribute for firing a server side Ajax call and doing the validation on the server side, keeping the existing form intact.

Setting up the Remote Attribute

To add the Async validation functionality we need to decorate our Model with an Attribute called ‘Remote’ and specify the Controller and Action method that will handle the Async request. This is done as follows

Step 1: Open the AccountModels.cs and navigate to the ‘RegisterModels’ class. On the UserName property, add the Remote attribute as follows. The ‘VerifyUserExists’ is the Action method on the ‘Account’ controller. We could specify a named parameter in the Remote attribute as ErrorMessage=’User Already Exists’, but we want to reuse the same message as the server side validation. So instead of duplicating text, we will retrieve it appropriately in the Action method.

register-models-class-updated

Step 2: Open the AccountController.cs and add a Method VerifyUserExists. This returns a JsonResult. Decorate the method with AllowAnonymous because we want to access this method at the time of Registration, which is done Anonymously.

Step 3: In the VerifyUserExists method, check for the UserName using the Membership provider. If user already exists, return the same error message that is returned on Server Side validation. If the user does not exist return true.

verify-user-exists-method

The Unobtrusive jQuery validator will treat any non-boolean value as false. So if no explicit ErrorMessage is provided, it will display the value that is returned. In our case we are returning the error message that we want to display.

Step 4: Open the Register.cshtml. The form uses a ValidationSummary helper to show a summary of all errors on server side submits. However we want to show the validation result immediately. So we add a @Html.ValidationMessageFor(m => m.UserName) to the UserName field. So if the Remote validator comes back with error it is shown immediately next to the field.

That’s it, we are all set with our Async validation for UserName. Run the application and try to create another user with the same name as the existing user. Notice how the error message comes up almost instantly. Warning the user before too many other elements have been populated.

username-validation-async

Conclusion

Remote attributes provide an easy way for doing server side validations where client-side validation is not possible and we want to provide an Ajaxified experience to the end-user that does not involve a lot of full page Postbacks.

ASP.NET MVCs validation framework is pretty extensive and has other extensibility points like custom Client Side validators. We will explore these in future, but for mandatory server side validations Remote attributes sit in a nice middle-ground of doing server side validations and maintaining near-client-side-validation interactive-ness.

Download the Zip file

Repository at - https://github.com/devcurry/RemoteValidationAttribute

ASP.NET MVC: Displaying Partial Views using jQuery UI Dialog Boxes

One of my clients had a requirement in an ASP.NET MVC 3 project where they wanted to load a View in a Modal Dialog that can then be moved around. I suggested a solution where the jQuery UI Dialog can be used to load an MVC Partial View.

The jQuery UI Dialog object provides properties like width, resizable, draggable etc. to customize the dialog layout and behavior. This object provides functions like ‘open’ and ‘close’ where you can write script so that on ‘open’ function, the Partial View can be loaded in it.

For this article, I am using Department Table and using ADO.NET EF. The Model is created in MVC 3 application as shown below:

mvc-dept-table

Step 1: Create a new MVC 3 project, and in its Model folder, add the Department Table using ADO.NET EF. The Entities class name for the ADONET EF will be CompanyEntities.

Step 2: Right click on the Controller folder and add a Department Controller in it. Write the following code in the Department controller’s constructor and the Index action method.

CompanyEntities objContext;
public DepartmentController()
{
     objContext = new CompanyEntities();
     objDeptCollection = new DepartmentCollection();
}


//

// GET: /Department/


public ActionResult Index()
{
    var Departments = objContext.Departments.ToList();
    return View(Departments); 


}

Step 3: Add the Index View in application by right clicking on Index method and select Model class as Department and the Scaffold Template as “List”. You will get the Department subfolder in Views folder and Index.cshtml in it.

Step 4: Right click on the Department subfolder and add Strongly Typed partial View in it with Scaffold Template as ‘Create’ and Model class as ‘Department’ as shown  below:

mvc-partial-view

Step 5: The Create method in the Department controller class is as follows:


public ActionResult Create()
{
    Department objDept = new Department(); 
    return PartialView("CreateDepartment",objDept); 
}



[HttpPost]
public ActionResult Create(Department objDept)
{
    try
    {
        objContext.AddToDepartments(objDept);
        objContext.SaveChanges();
        return RedirectToAction("Index");
    }


    catch (Exception)
    {
        return PartialView("CreateDepartment", objDept); 
    }

}


Note that the create method with Http Get returns the Partial View created in the Previous Task.

Step 6: In the Index.cshtml, add a Html button as shown below:


<button id="btnCreate" value="Create" 
    style="width:90px;height:50px">Create
</button>

Step 7: Add the html <div> tag in the Index.cshtml as shown below:


<div id="departmentdialog" title="Add Department" 
style="overflow: hidden;background-color:Yellow;
border-bottom-width:5;background-color:Red"></div>

Step 8: Add the following script in the Index.cshtml page. This will create an object of Dialog and the partial view will be displayed in it by using its open method as shown below:


<script type="text/javascript" language="javascript">
$(document).ready(function () {


    $("#btnCreate").click(function () {
        InitializeDialog($("#departmentdialog"));

       $("#departmentdialog").dialog("open");
    });



    //Method to Initialize the DialogBox
    function InitializeDialog($element) {


        $element.dialog({
            autoOpen: false,
            width: 400,
            resizable: true,
            draggable: true,
            title: "Department Operation",
            model: true,
            show: 'slide',
            closeText: 'x',
            dialogClass: 'alert',
            closeOnEscape: true,
            open: function (event, ui) {
                //Load the Partial View Here using Controller and Action
                $element.load('/Department/Create');
            },

            close: function () {
                $(this).dialog('close');
            }

        });

    }
});


</script>

Note: The above code shows that the ‘InitializeDialog’ script method defines ‘dialog’ object for the element id passed to the method. The Open function of dialog object makes call to the ‘load’ method of the element (here in case, HTML <div> of name ‘departmentdialog’), this takes the Department Controllers ‘Create’ action.

Step 9: Run the application and navigate to the Index of the Department controller. From the Index View, click on the ‘Create’ button. The partial View Rendered will be as below:


mvc-result

Conclusion:

Partial Views in MVC can be used as independent View modules to create either a web part like behavior or as we saw above, for Modal data representations.

ReadOnlyDictionary in .NET 4.5

Yes! For people doing custom implementation to create a Read Only Dictionary, there is now a .NET BCL implementation of the same in .NET 4.5.

For the Uninitiated the question is - Why do you need a ReadOnlyDictionary in the first place?

A ReadOnlyDictionary is a useful data container when you are sending data across layers of an application and you want to ensure the data is not modified across the layer.

A good use case for this is Configuration information that is critical for functioning of an application. We may want multiple layers of the application to have access to the configuration information (and a dictionary is a very good way to pass configuration around) but no one should be able to update the configuration directly without going through the required checks and balances. In the following sample, we will look a small such sample.

A Read-only Configuration

Step 1: Create a new Console Application in Visual Studio 2012 CP. Name the Solution ‘ReadOnlyCollectionSample’.

Step 2: Add two Window Class Library projects, ConfigurationLibrary and ConfigurationConsumer.

Step 3: In the ConfigurationLibrary project, add a Class called ConfigurationContainer

solution-structure

Step 4: Setting up the ConfigurationContainer

- In the ConfigurationContainer, add a field _mutableConfiguration for type Dictionary<string, string>. This is where we will load our configuration.

- In the constructor, initialize the _mutableConfiguration dictionary and add some key value pairs to it.

- Add a property called Configuration with the type ReadOnlyDictionary<string, string> with a getter only. The Getter will return a new instance of ReadOnlyDictionary<string, string>. The Read Only Dictionary is initiated using the _mutableConfiguration.

- Add a public method AddToConfiguration(key, value). This method will add/update a configuration key/value pairs from outside.

- Add a method ConfigurationAllowed that returns a Boolean. This contains the logic that decides if a particular configuration parameter can be updated or not and update it accordingly. Essentially we have restricted users from updated the Configuration and we will be controlling the update via this method.

- The final class looks as follows:

configuration-container

Step 5: Setting up the ConfigurationConsumer

- Rename the Class1 to ConfigurationConsumer

- Declare a field of type IReadOnlyDictionary<string, string> called _config.

- In the Constructor initialize the _config field by using the Configuration property of an instance of ConfigurationContainer

- Add a method DoSomething() that checks if a “key” called configuration exists and prints a message with the value if it does. If the “key” does not exist it prints a different message.

- Add another method called BeNaughtyWithConfiguration(). Try to cast the _config read-only dictionary into an ordinary IDictionary. Now add a key to the IDictionary instance. The full listing is as follows

configuration-consumer

Step 6: Using the Configuration in ReadOnlyCollectionSample

- In the Program.cs’ main method instantiate the ConfigurationConsumer and call the DoSomething() method

- Add a Console.ReadLine() to wait for user input before executing the next line.

- Call the BeNaughtyWithConfiguration() method

- The Final code is as follows

program-main-method

Running the Sample

Build and run the sample. The output on the console will be something as follows:

console-output-1

As we see, the value from the Read only dictionary was extracted successfully.

Next we hit enter and the code tries to execute the BeNaughtyWithConfiguration method. Wham! We get the following exception:

not-supported-exception

As we can see, our ReadOnly configurations are safe from type conversion into updatable counterparts.

If you add a watch for the convertToReadWrite.IsReadOnly property, you will find it to be ‘True’.

watch-isreadonly-true

A Note about Dictionary of Mutable Objects

In our above sample, the Dictionary was that of primitive type ‘string’ that is itself immutable. However if you had a read only dictionary of type say ConfigElement, where ConfigElement is defined as follows:

config-element

The ReadOnlyDictionary in this case would not be able to prevent changes to the ConfigElement instance. So if someone retrieved the ConfigElement from the readonly dictionary and updated the Value property, the property would get change in the instance that’s in the Dictionary.

updating-mutable-objects

This code will give us the following output

updated-mutable-objects

As we can see the element got updated in the Dictionary.

Conclusion

To conclude, the new ReadOnlyDictionary<T,T> generic type in .NET 4.5 fulfills a long standing feature request for the BCL. It will be very useful for scenarios where read only Dictionaries need to be exposed. One such case is shown above.

The final code (including use of the ConfigElement type) is available here. Repo at: https://github.com/devcurry/ReadOnlyCollectionSample

Note: We have tested the code on the following combinations
1. VS 2012 RC + Windows 7
2. Win8 CP with VS11 Beta to run the code sample. It is going to work on Win8 RP + VS 2012 RC as well.