3

我已经为文本框和多行文本框的合适拼写检查器研究了很长时间。

我可以看到这个功能是为 firefox 内置的,但它不存在于 chrome 中。

我正在查看 jquery spellchecker - badsyntax 提供的所有拼写检查演示,我发现它非常好用。

这是链接 http://jquery-spellchecker.badsyntax.co/

但我的问题是 - 拼写检查器使用 php webservices,我想在我的 ASP.net Web 应用程序中使用它。

有什么办法可以让我使用 asp.net 网络服务运行它吗?

请给我一个解决方案。

4

3 回答 3

1

我是该插件的作者,我真的很想合并一些其他的 web 服务实现。

这最近在我的谷歌警报中弹出,但我无法验证它是否有效:

于 2013-03-12T12:05:36.117 回答
1

大家好:Veerendra Prabhu,badsyntax;我已经集成了 Nhunspell 和 asp.net Web 服务(.asmx),目前我正在尝试将 jquery spellchecker - badsyntax 集成到项目中,我的 jquery spellchecker 现在与我的网络服务连接,但我仍在处理返回的数据我的网络服务类型允许 jquery spellcheker 发挥它的魔力,但我认为它的东西。

我的想法来自:

deepinthecode.com

以下是我使用的一些想法:

我使用了 NHusnpell,它有助于在传递的文本中获取不正确的单词并查看字典(以 .oxt 格式下载的打开办公室,但您必须使用 zip 来获取 en_US.aff 和 en_US.dic)此文件需要位于bin 目录。

在 Glabal.asax 文件中,我创建了一个静态的 NHuspell 实例来完成所有工作。

public class Global : System.Web.HttpApplication
{
    static SpellEngine spellEngine;
    static public SpellEngine SpellEngine { get { return spellEngine; } }

    protected void Application_Start(object sender, EventArgs e)
    {
        try
        {
            string dictionaryPath = Server.MapPath("Bin") + "\\";
            Hunspell.NativeDllPath = dictionaryPath;

            spellEngine = new SpellEngine();
            LanguageConfig enConfig = new LanguageConfig();
            enConfig.LanguageCode = "en";
            enConfig.HunspellAffFile = dictionaryPath + "en_us.aff";
            enConfig.HunspellDictFile = dictionaryPath + "en_us.dic";
            enConfig.HunspellKey = "";
            //enConfig.HyphenDictFile = dictionaryPath + "hyph_en_us.dic";
            spellEngine.AddLanguage(enConfig);
        }
        catch (Exception ex)
        {
            if (spellEngine != null)
                spellEngine.Dispose();
        }
    }

    ...

    protected void Application_End(object sender, EventArgs e)
    {
        if (spellEngine != null)
            spellEngine.Dispose();
        spellEngine = null;

    }
}

然后我为 Get_Incorrect_Words 和 Get_Suggestions 方法创建了一个 ASMX Web 服务

 /// <summary>
/// Summary description for SpellCheckerService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    
[ScriptService()]
public class SpellCheckerService : System.Web.Services.WebService
{      

    [WebMethod]
    //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string get_incorrect_words(string words)
    {
        Dictionary<string, string> IncorrectWords = new Dictionary<string, string>();

        List<string> wrongWords = new List<string>();

        var palabras = words.Split(' ');

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

            if (!correct){

                wrongWords.Add(word);
            }
        }

        IncorrectWords.Add("data", wrongWords[0]);

        return wrongWords[0];
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<string> get_suggestions(string word)
    {
        List<string> suggestions = new List<string>();
        suggestions = Global.SpellEngine["en"].Suggest(word);
        suggestions.Sort();
        return suggestions;
    }

最后,我修改了 jquery.Spellchecker.js 中对 get_incorrect_words 和 get_suggestions 的调用

 /* Config
   *************************/

  var defaultConfig = {
    lang: 'en',
    webservice: {
        path: 'SpellCheckerService.asmx/get_incorrect_words'
      //,driver: 'LabNET'
    },
    local: {
      requestError: 'There was an error processing the request.',
      ignoreWord: 'Ignore word',
      ignoreAll: 'Ignore all',
      ignoreForever: 'Add to dictionary',
      loading: 'Loading...',
      noSuggestions: '(No suggestions)'
    },
    suggestBox: {
      numWords: 5,
      position: 'above',
      offset: 2,
      appendTo: null
    },
    incorrectWords: {
      container: 'body', //selector
      position: null //function
    }
  };

  var pluginName = 'spellchecker';

...

     /* Spellchecker web service
   *************************/

  var WebService = function(config) {

    this.config = config;

    this.defaultConfig = {
      url: config.webservice.path,
      //contentType: "application/json; charset=utf-8",
      type: 'POST',
      dataType: 'text',
      cache: false,
      data: JSON.stringify({
        lang: config.lang,
        driver: config.webservice.driver
      }, null,2) ,
      error: function() {
        alert(config.local.requestError);
      }.bind(this)
    };
  };

  WebService.prototype.makeRequest = function(config) {

    var defaultConfig = $.extend(true, {}, this.defaultConfig);

    return $.ajax($.extend(true, defaultConfig, config));
  };

  WebService.prototype.checkWords = function (text, callback) {
      //action: 'get_incorrect_words',
      //JSON.stringify({

      //    text: text
      //}, null, 2)

      return this.makeRequest(
          {
              data: { words: text },
              success: callback
    });
  };

  WebService.prototype.getSuggestions = function (word, callback) {
      //action: 'get_suggestions',
    return this.makeRequest({
        data: JSON.stringify({

        word: word
      }, null, 2),
      success: callback
    });
  };
于 2013-03-12T15:12:55.047 回答
0

我找到了该问题的解决方案,下面是返回 jquery 拼写检查器的 JSON 响应的 web 服务

此代码是在中找到的代码的修改版本

github.com/jackmyang/jQuery-Spell-Checker-for-ASP.NET

     /// <summary>


  using System;
  using System.Collections.Generic;
  using System.Net;
  using System.Text;
  using System.Web;
  using System.Xml;

< %@ WebHandler Language="C#" Class="JQuerySpellCheckerHandler2" %>



/// <summary>
/// jQuery spell checker http handler class. Original server-side code was written by Richard Willis in PHP.
/// This is a version derived from the original design and implemented for ASP.NET platform.
/// 
/// It's very easy to use this handler with ASP.NET WebForm or MVC. Simply do the following steps:
///     1. Include project jquery.spellchecker assembly in the website as a reference
///     2. Include the httphandler node in the system.web node for local dev or IIS 6 or below
/// <example>
///     <![CDATA[
///         <system.web>
///             <httpHandlers>
///                 <add verb="GET,HEAD,POST" type="jquery.spellchecker.JQuerySpellCheckerHandler" path="JQuerySpellCheckerHandler.ashx"/>
///             </httpHandlers>
///         </system.web>
///     ]]>
/// </example>
///     3. If IIS7 is the target web server, also need to include the httphandler node in the system.webServer node
/// <example>
///     <![CDATA[
///         <system.webServer>
///             <handlers>
///                 <add verb="GET,HEAD,POST" name="JQuerySpellCheckerHandler" type="jquery.spellchecker.JQuerySpellCheckerHandler" path="JQuerySpellCheckerHandler.ashx"/>
///             </handlers>
///         </system.webServer>
///     ]]>
/// </example>
///     4. On the web page which included the spell checker, set the 'url' property to '~/JQuerySpellCheckerHandler.ashx'
/// <example>
///     <![CDATA[
///         $("#text-content")
///             .spellchecker({
///                 url: "~/JQuerySpellCheckerHandler.ashx",
///                 lang: "en",
///                 engine: "google",
///                 suggestBoxPosition: "above"
///         })
///     ]]>
/// </example>
/// </summary>
/// <remarks>
/// Manipulations of XmlNodeList is used for compatibility concern with lower version of .NET framework,
/// alternatively, they can be simplified using 'LINQ for XML' if .NET 3.5 or higher is available.
/// </remarks>
public class JQuerySpellCheckerHandler2 : IHttpHandler
{
    #region fields

    // in case google changes url, value of GoogleSpellCheckRpc can be stored in web.config instead to avoid code re-compilation
    private const string GoogleSpellCheckRpc = "https://www.google.com/tbproxy/spell?";
    private const string GoogleFlagTextAlreadClipped = "textalreadyclipped";
    private const string GoogleFlagIgnoreDups = "ignoredups";
    private const string GoogleFlagIgnoreDigits = "ignoredigits";
    private const string GoogleFlagIgnoreAllCaps = "ignoreallcaps";

    #endregion

    #region properties

    /// <summary>
    /// Gets or sets a value indicating whether [ignore duplicated words].
    /// </summary>
    /// <value><c>true</c> if [ignore dups]; otherwise, <c>false</c>.</value>
    private bool IgnoreDups { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether [ignore digits].
    /// </summary>
    /// <value><c>true</c> if [ignore digits]; otherwise, <c>false</c>.</value>
    private bool IgnoreDigits { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether [ignore all capitals].
    /// </summary>
    /// <value><c>true</c> if [ignore all caps]; otherwise, <c>false</c>.</value>
    private bool IgnoreAllCaps { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether [text alread clipped].
    /// </summary>
    /// <value><c>true</c> if [text alread clipped]; otherwise, <c>false</c>.</value>
    private bool TextAlreadClipped { get; set; }

    #endregion

    #region Implementation of IHttpHandler

    /// <summary>
    /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. 
    /// </param>
    public void ProcessRequest(HttpContext context)
    {
        string engine = context.Request.Form[1];
        string lang = context.Request.Form["lang"];
        string text = context.Request.Form[3];
        string suggest = context.Request.Form[2];
        SetSwitches(context);            
        string result = SpellCheck(text, lang, engine, suggest);
        context.Response.ContentType = "application/js";
        string jsonStr = "{\"outcome\":\"success\",\"data\":[" + result + "]}";
        if (suggest == "get_incorrect_words")
        {
            context.Response.Write(jsonStr);
        }
        else
        {
            context.Response.Write(result);
        }
    }

    /// <summary>
    /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
    /// </summary>
    /// <returns>
    /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
    /// </returns>
    public bool IsReusable
    {
        get { return false; }
    }

    #endregion

    #region private methods

    /// <summary>
    /// Spells the check.
    /// </summary>
    /// <param name="text">The text.</param>
    /// <param name="lang">The lang.</param>
    /// <param name="engine">The engine.</param>
    /// <param name="suggest">The suggest.</param>
    /// <returns></returns>
    private string SpellCheck(string text, string lang, string engine, string suggest)
    {
        if (0 == string.Compare(suggest, "undefined", StringComparison.OrdinalIgnoreCase))
        {
            suggest = string.Empty;
        }
        if (0 != string.Compare(engine, "google", true))
        {
            throw new NotImplementedException("Only google spell check engine is support at this moment.");
        }
        string xml;
        List<string> result;
        if (string.IsNullOrEmpty(suggest) || suggest == "get_incorrect_words")
        {
            xml = GetSpellCheckRequest(text, lang);
            result = GetListOfMisspelledWords(xml, text);
        }
        else
        {
            xml = GetSpellCheckRequest(text, lang);
            result = GetListOfSuggestWords(xml, text);
        }
        return ConvertStringListToJavascriptArrayString(result);
    }

    /// <summary>
    /// Sets the boolean switch.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="queryStringParameter">The query string parameter.</param>
    /// <returns></returns>
    private static bool SetBooleanSwitch(HttpContext context, string queryStringParameter)
    {
        byte tryParseZeroOne;
        string queryStringValue = context.Request.QueryString[queryStringParameter];
        if (!string.IsNullOrEmpty(queryStringValue) && byte.TryParse(queryStringValue, out tryParseZeroOne))
        {
            if (1 < tryParseZeroOne || 0 > tryParseZeroOne)
            {
                throw new InvalidOperationException(string.Format("Query string parameter '{0}' only supports values of 1 and 0.", queryStringParameter));
            }
            return tryParseZeroOne == 1;
        }
        return false;
    }

    /// <summary>
    /// Gets the list of suggest words.
    /// </summary>
    /// <param name="xml">The source XML.</param>
    /// <param name="suggest">The word to be suggested.</param>
    /// <returns></returns>
    private static List<string> GetListOfSuggestWords(string xml, string suggest)
    {
        if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(suggest))
        {
            return null;
        }
        // 
        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(xml);
        if (!xdoc.HasChildNodes)
        {
            return null;
        }
        XmlNodeList nodeList = xdoc.SelectNodes("//c");
        if (null == nodeList || 0 >= nodeList.Count)
        {
            return null;
        }
        List<string> list = new List<string>();
        foreach (XmlNode node in nodeList)
        {
            list.AddRange(node.InnerText.Split('\t'));
            return list;
        }
        return list;
    }

    /// <summary>
    /// Gets the list of misspelled words.
    /// </summary>
    /// <param name="xml">The source XML.</param>
    /// <param name="text">The text.</param>
    /// <returns></returns>
    private static List<string> GetListOfMisspelledWords(string xml, string text)
    {
        if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(text))
        {
            return null;
        }
        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(xml);
        if (!xdoc.HasChildNodes)
        {
            return null;
        }
        XmlNodeList nodeList = xdoc.SelectNodes("//c");
        if (null == nodeList || 0 >= nodeList.Count)
        {
            return null;
        }
        List<string> list = new List<string>();
        foreach (XmlNode node in nodeList)
        {
            int offset = Convert.ToInt32(node.Attributes["o"].Value);
            int length = Convert.ToInt32(node.Attributes["l"].Value);
            list.Add(text.Substring(offset, length));
        }
        return list;
    }

    /// <summary>
    /// Constructs the request URL.
    /// </summary>
    /// <param name="text">The text which may contain multiple words.</param>
    /// <param name="lang">The language.</param>
    /// <returns></returns>
    private static string ConstructRequestUrl(string text, string lang)
    {
        if (string.IsNullOrEmpty(text))
        {
            return string.Empty;
        }
        lang = string.IsNullOrEmpty(lang) ? "en" : lang;
        return string.Format("{0}lang={1}&text={2}", GoogleSpellCheckRpc, lang, text);
    }

    /// <summary>
    /// Converts the C# string list to Javascript array string.
    /// </summary>
    /// <param name="list">The list.</param>
    /// <returns></returns>
    private static string ConvertStringListToJavascriptArrayString(ICollection<string> list)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append("[");
        if (null != list && 0 < list.Count)
        {
            bool showSeperator = false;
            foreach (string word in list)
            {
                if (showSeperator)
                {
                    stringBuilder.Append(",");
                }
                stringBuilder.AppendFormat("\"{0}\"", word);
                showSeperator = true;
            }
        }
        stringBuilder.Append("]");
        return stringBuilder.ToString();
    }

    /// <summary>
    /// Sets the switches.
    /// </summary>
    /// <param name="context">The context.</param>
    private void SetSwitches(HttpContext context)
    {
        IgnoreAllCaps = SetBooleanSwitch(context, GoogleFlagIgnoreAllCaps);
        IgnoreDigits = SetBooleanSwitch(context, GoogleFlagIgnoreDigits);
        IgnoreDups = SetBooleanSwitch(context, GoogleFlagIgnoreDups);
        TextAlreadClipped = SetBooleanSwitch(context, GoogleFlagTextAlreadClipped);
    }

    /// <summary>
    /// Requests the spell check and get the result back.
    /// </summary>
    /// <param name="text">The text.</param>
    /// <param name="lang">The language.</param>
    /// <returns></returns>
    private string GetSpellCheckRequest(string text, string lang)
    {
        string requestUrl = ConstructRequestUrl(text, lang);
        string requestContentXml = ConstructSpellRequestContentXml(text);
        byte[] buffer = Encoding.UTF8.GetBytes(requestContentXml);

        WebClient webClient = new WebClient();
        webClient.Headers.Add("Content-Type", "text/xml");
        try
        {
            byte[] response = webClient.UploadData(requestUrl, "POST", buffer);
            return Encoding.UTF8.GetString(response);
        }
        catch (ArgumentException)
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// Constructs the spell request content XML.
    /// </summary>
    /// <param name="text">The text which may contain multiple words.</param>
    /// <returns></returns>
    private string ConstructSpellRequestContentXml(string text)
    {
        XmlDocument doc = new XmlDocument(); // Create the XML Declaration, and append it to XML document
        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(declaration);
        XmlElement root = doc.CreateElement("spellrequest");
        root.SetAttribute(GoogleFlagTextAlreadClipped, TextAlreadClipped ? "1" : "0");
        root.SetAttribute(GoogleFlagIgnoreDups, IgnoreDups ? "1" : "0");
        root.SetAttribute(GoogleFlagIgnoreDigits, IgnoreDigits ? "1" : "0");
        root.SetAttribute(GoogleFlagIgnoreAllCaps, IgnoreAllCaps ? "1" : "0");
        doc.AppendChild(root);
        XmlElement textElement = doc.CreateElement("text");
        textElement.InnerText = text;
        root.AppendChild(textElement);
        return doc.InnerXml;
    }

    #endregion
}

你也可以使用这个javascript:

      // Replace the Spellchecker.php path with Asp.net ashx path

    spellchecker = new $.SpellChecker(body, {
        lang: 'en',
        parser: 'html',
        webservice: {
          path: "../Includes/JS/spellify/JQuerySpellCheckerHandler2.ashx",
          driver: 'google'
        },
        suggestBox: {
          position: 'below'
        }
      });

      // Bind spellchecker handler functions
      spellchecker.on('check.success', function() {
        alert('There are no incorrectly spelt words.');
      });

      spellchecker.check();
于 2013-03-14T06:46:00.833 回答