Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

Using NHunSpell in ASP.NET with JSON Web Service and jQuery

Rate me:
Please Sign up or sign in to vote.
4.78/5 (5 votes)
14 May 2010CPOL3 min read 37.6K   1.3K   13   12
Demonstrates how to use the NHunSpell library in an ASP.NET application by calling web services using jQuery

Introduction

This article builds on the excellent open source projects JSSpellCheck and NHunSpell which provided the majority of code for this article.

Background

A project I was working on required the ability to spell check multiple words in a text area.

The examples provided with the NHunSpell source or online at Spell-Check-Thesaurus work on a 'one word at a time' basis.

The example provided with JSSpellCheck was exactly what I was looking for, however, the example server script provided with the source was written in PHP and I needed to implement this in ASP.NET.

This article will show you how to link the jQuery front end to the NHunSpell component that will be hosted by your web server.

The communication from client to server will use a JSON web service.

Included in this Download

The download file contains all the source required to run the web project. The client relies heavily on jQuery and jQuery UI which I have bundled into a single script file.

To keep the size of the download to a minimum, I've only included the x86 version of the NHunSpell component and the English dictionary. If you require different versions or languages, please visit the NHunSpell home page linked above.

Using the Code

The first thing to do was to create the web service that would provide the spell checking functionality. Not surprisingly, the service in this example is called SpellCheckerService.

C#
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Dictionary<string, List<string>> CheckSpelling(List<string> words)
{
    Dictionary<string, List<string>> results = new Dictionary<string, List<string>>();

    // Check spelling of each word that has been passed to the method
    foreach (string word in words)
    {
        bool correct = Global.SpellEngine["en"].Spell(word);

        // If the word is spelled incorrectly, add it to the list of words to be
        // returned along with suggestions
        if (!correct)
        {
            List<string> suggestions = Global.SpellEngine["en"].Suggest(word);
            suggestions.Sort();

            results.Add(word, suggestions);
        }
    }
    return results;
}

How the Method Words

From the client, you call this method and pass it an array of words that you want to spell check. For example:

C#
array[0] = 'This'
array[1] = 'Is'
array[2] = 'Some'
array[3] = 'Example'
array[4] = 'Text'

The service then works through each word in the list and uses the spelling engine to check if the word is spelled correctly. If it is incorrect, it adds it to a list of items to return as JSON to the caller.

In the documentation for jquery.spellchecker, you will note that the source expects the method to return data as a hash of 'misspelledword' => ['list', 'of', 'suggestions'] pairs.

To return data in the correct format, we therefore use a generic type of Dictionary<string, List<string>>.

Project Configuration

The project in this example is using .NET 2.0 and has a dependency on System.Web.Extensions (1.0.61025.0). This is required for us to be able to call the web service from script code by marking the method with the [ScriptMethod] attribute.

In your configuration file, you also need to add some entries to handle calls to the web service:

XML
<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx"
      type="System.Web.Script.Services.ScriptHandlerFactory,
      System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
      PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule,
      System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
      PublicKeyToken=31bf3856ad364e35"/>
</httpModules>

On the Client

In the page where you want to add spell checking, add a button to trigger the spell check and create an onclick event handler to start the spell checking process:

JavaScript
 var SpellCheckOptions = { learn : false, 
	serverScriptURL : 'SpellCheckerService.asmx' };

function spellCheckTextArea(targetId) {
	var $textarea = $(targetId);

	//this callback will be called when the spellcheck is
	//complete. In this case we set the value of the target
	//textarea to the corrected text.
	var callback = function(textInfos) {
	  $textarea.val(textInfos[0].text);	
	}
	
var spellcheck = JQSpellCheckDialog.create
	({text : $textarea.val()}, callback, SpellCheckOptions);
	spellcheck.open();
}

You pass the function the ID of the textarea that you want to spell check. The function creates the dialog, passes in the text to spell check and initiates the web service call.

There were a couple of minor tweaks to make to the JsSpellCheck code in order to work with the web service using method signature above.

* In SpellCheck.internal.MisspelledWords.prototype.check, the method gathers your input and creates a list of unique words to pass to the server. In the original source, the call to the server was as follows:

JavaScript
 server.check(uniqueWords.join("\n"), function(result) {

	self._misspelledWords[textObject._identifier] = result;            
	afterCheckCallback();  
}); 

I've changed this to just pass the entire array, as this is what is expected in web service method CheckSpelling:

JavaScript
server.check(uniqueWords, function(result) {
	self._misspelledWords[textObject._identifier] = result;            
	afterCheckCallback();            
}); 

That's It!

That's all that was required in order to use the functionality of both the jQuery and NHunspell examples.

Many thanks to Thomas Maierhofer for the NHunSpell wrapper and Lenny Marks for the JSSpellCheck scripts. 99% of all the code was written by them and it was a very easy job to quickly provide full spell checking based on their releases.

To Do

The NHunSpell component provides excellent functionality that we could utilize in the web service.

I haven't implemented the functionality required for the server to 'Learn' words (I'm a bit dubious about exposing this to users? Potential for abuse!) and have also left the Thesaurus capability from this release.

Further Reading

History

  • May 2010 - Initial release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Dixit Mirtkar18-Dec-12 22:47
Dixit Mirtkar18-Dec-12 22:47 
Good Article....!!!
QuestionDoesnt work if deployed to IIS Pin
manchu738-Jun-12 7:08
manchu738-Jun-12 7:08 
QuestionExcelente solution but.... something doesn't work for me Pin
DCrognale16-Jun-10 11:54
DCrognale16-Jun-10 11:54 
AnswerRe: Excelente solution but.... something doesn't work for me Pin
Dylan Morley17-Jun-10 1:48
Dylan Morley17-Jun-10 1:48 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
DCrognale17-Jun-10 3:40
DCrognale17-Jun-10 3:40 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
DCrognale17-Jun-10 6:25
DCrognale17-Jun-10 6:25 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
Dylan Morley17-Jun-10 21:41
Dylan Morley17-Jun-10 21:41 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
joegore27-Jun-13 11:23
joegore27-Jun-13 11:23 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
Dylan Morley27-Jun-13 22:26
Dylan Morley27-Jun-13 22:26 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
joegore22-Jul-13 8:40
joegore22-Jul-13 8:40 
GeneralRe: Excelente solution but.... something doesn't work for me Pin
joegore22-Jul-13 8:52
joegore22-Jul-13 8:52 
GeneralGood work Pin
Donsw5-Jun-10 16:17
Donsw5-Jun-10 16:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.