Click here to Skip to main content
11,409,097 members (67,932 online)
Click here to Skip to main content

Tagged as

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

, 14 May 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

[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:

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:

  <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:

 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:

 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:

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)

Share

About the Author

Dylan Morley
Technical Lead
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 804202618-Dec-12 23:47 
QuestionDoesnt work if deployed to IIS Pinmembermanchu738-Jun-12 8:08 
QuestionExcelente solution but.... something doesn't work for me PinmemberMember 410312916-Jun-10 12:54 
AnswerRe: Excelente solution but.... something doesn't work for me PinmemberDylan Morley17-Jun-10 2:48 
GeneralRe: Excelente solution but.... something doesn't work for me PinmemberMember 410312917-Jun-10 4:40 
GeneralRe: Excelente solution but.... something doesn't work for me PinmemberDCrognale17-Jun-10 7:25 
GeneralRe: Excelente solution but.... something doesn't work for me PinmemberDylan Morley17-Jun-10 22:41 
GeneralRe: Excelente solution but.... something doesn't work for me Pinmemberjoegore27-Jun-13 12:23 
GeneralRe: Excelente solution but.... something doesn't work for me PinmemberDylan Morley27-Jun-13 23:26 
GeneralRe: Excelente solution but.... something doesn't work for me Pinmemberjoegore22-Jul-13 9:40 
GeneralRe: Excelente solution but.... something doesn't work for me Pinmemberjoegore22-Jul-13 9:52 
GeneralGood work PinmemberDonsw5-Jun-10 17:17 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150414.5 | Last Updated 14 May 2010
Article Copyright 2010 by Dylan Morley
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid