65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP.NET 中使用 NHunSpell,结合 JSON Web Service 和 jQuery

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (5投票s)

2010年5月14日

CPOL

3分钟阅读

viewsIcon

39156

downloadIcon

1332

演示如何通过使用 jQuery 调用 Web 服务,在 ASP.NET 应用程序中使用 NHunSpell 库

引言

本文基于优秀的开源项目 JSSpellCheck NHunSpell,本文的大部分代码都来自这些项目。

背景

我正在进行的一个项目需要能够拼写检查文本区域中的多个单词。

NHunSpell 源代码或在线 Spell-Check-Thesaurus 提供的示例都是基于“一次一个单词”的方式。

JSSpellCheck 提供的示例正是我所需要的,但是,源代码提供的示例服务器脚本是用 PHP 编写的,我需要用 ASP.NET 实现它。

本文将向您展示如何将 jQuery 前端链接到 NHunSpell 组件,该组件将由您的 Web 服务器托管。

客户端到服务器的通信将使用 JSON Web 服务。

下载内容包括

下载文件包含运行 Web 项目所需的所有源代码。 客户端严重依赖 jQuery jQuery UI,我已将它们捆绑到一个脚本文件中。

为了使下载文件的大小最小化,我只包含了 NHunSpell 组件的 x86 版本和英语词典。 如果您需要不同的版本或语言,请访问上面链接的 NHunSpell 主页。

Using the Code

首先要做的是创建提供拼写检查功能的 Web 服务。 毫不奇怪,本示例中的服务称为 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;
}

方法单词如何运作

从客户端,您调用此方法并传递一个您要拼写检查的单词数组。 例如

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

然后,该服务处理列表中的每个单词,并使用拼写引擎检查该单词的拼写是否正确。 如果不正确,它会将其添加到要作为 JSON 返回给调用者的项目列表中。

jquery.spellchecker 的文档中,您会注意到该源代码期望该方法以 'misspelledword' => ['list', 'of', 'suggestions'] 键值对的形式返回数据。

因此,为了以正确的格式返回数据,我们使用泛型类型 Dictionary<string, List<string>>

项目配置

本示例中的项目使用 .NET 2.0,并且依赖于 System.Web.Extensions (1.0.61025.0)。 这是我们能够通过使用 [ScriptMethod] 属性标记方法,从脚本代码调用 Web 服务所必需的。

在您的配置文件中,您还需要添加一些条目来处理对 Web 服务的调用

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

在客户端

在您要添加拼写检查的页面中,添加一个按钮以触发拼写检查,并创建一个 onclick 事件处理程序以启动拼写检查过程

 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();
}

您将要拼写检查的文本区域的 ID 传递给该函数。 该函数创建对话框,传入要拼写检查的文本,并启动 Web 服务调用。

为了使用上面的方法签名与 Web 服务一起使用,需要对 JsSpellCheck 代码进行一些小的调整。

* 在 SpellCheck.internal.MisspelledWords.prototype.check 中,该方法收集您的输入并创建一个唯一单词列表以传递给服务器。 在原始源代码中,对服务器的调用如下

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

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

我已将其更改为仅传递整个数组,因为这是 Web 服务方法 CheckSpelling 中所期望的

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

就是这样!

这就是使用 jQuery 和 NHunspell 示例的功能所需要做的全部工作。

非常感谢 Thomas Maierhofer 提供的 NHunSpell 包装器和 Lenny Marks 提供的 JSSpellCheck 脚本。 所有代码的 99% 都是他们编写的,并且基于他们的版本,快速提供完整的拼写检查是一项非常容易的工作。

待办事项

NHunSpell 组件提供了我们可以在 Web 服务中利用的卓越功能。

我尚未实现服务器“学习”单词所需的功能(我对向用户公开此功能有点怀疑?存在被滥用的可能!),并且还从该版本中删除了词库功能。

延伸阅读

历史

  • 2010 年 5 月 - 初始发布
© . All rights reserved.