1

我创建了一个 aspx 表单。我正在使用 JQuery 验证引擎 ( http://www.position-relative.net/creation/formValidator/ ) 进行验证。

现在,我想用相同的红色气球错误提示(jquery 验证引擎的默认值)通知用户数据库中是否已经存在使用的 id。

我搜索了谷歌并得到了一些提示,但我对如何将参数传递给 ajaxcall 中涉及的 webmethod 感到困惑。

这是 github 站点 ( http://posabsolute.github.io/jQuery-Validation-Engine/#options/ajaxformvalidation ) 中给出的代码:

"ajaxUserCall": {
    "url": "~/Page.aspx/ajaxValidateFieldUser",
    "extraData": "name=eric",
    "extraDataDynamic": ['#user_id', '#user_email'],
    "alertText": "* This user is already taken",
    "alertTextOk": "All good!",
    "alertTextLoad": "* Validating, please wait"
}

我是通过以下方式理解的。如果我错了,请纠正我。

1) 我已将这段代码包含在“jquery.validationEngine.js”文件中。2) 我在 .Page.aspx' 中创建了 webmethod 'ajaxValidateFieldUser'。如下:

[WebMethod]
public static bool IsUserAvailable(string username)
{
if (record does not exist in table) // do not worry about this part of code. It is just for example
    return true;
else
    return false;
}

3) 在 userId 文本框中,我添加了类 'validate[ajaxValidateFieldUser]'。

4) 当然,我添加了正确的 jquery 文件,以便 JQuery ValidationEngine 的其他验证正常工作。

它不工作。我不知道如何将用户名参数(这是使用的 id 文本框的输入)传递给 webmethod。

4

2 回答 2

0

可以用这篇文章

jQuery 的 $.ajax() 函数有一个方便的选项:async,当设置为 false 时,它​​可以满足我们的需要——它在继续我们的成功函数之前等待来自服务器的响应。

function doesUsernameExist(source, arguments) {
var exists;
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Default.aspx/DoesUserExist",
    data: "{'username': '" + arguments.Value + "'}",
    dataType: "json",
    async: false,
    success: function(result) {
        exists = result.d;
    }
});
arguments.IsValid = !exists;
}

在后面的代码中创建了一个 webmethod

[WebMethod]
public static bool DoesUserExist(string username)
{
 if (record does not exist in table) // do not worry about this part of code. It is just for example
  return true;
 else
  return false;
}

html

<div>
 Username:
 <asp:TextBox runat="server" ID="UserNameTextBox" CausesValidation="true" />
</div>
<asp:CustomValidator runat="server"
    ID="UserNameExistsValidator"
    ControlToValidate="UserNameTextBox"
    ClientValidationFunction="doesUsernameExist"
    ErrorMessage="Username Already Exists" />
于 2014-01-25T05:40:34.137 回答
0

我正在使用 Inline Form Validation Engine 2.6.2,我也遇到了同样的问题,但我已经让它工作了。

在 jquery.validationEngine-en.js 中,

   // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
            "ajaxUserCall": {
                "url":"/Modules/CategoryModule/CategoryViewService.asmx/UserCheck",
                // you may want to pass extra data on the ajax call
                "extraDataDynamic": ['txtCategory', $('#txtCategory').val()],//ID of element you want to check with its value
                "alertTextOk": "All good",
                "alertText": "* This user is already taken",
                "alertTextLoad": "* Validating, please wait"
            },

HTML 代码:

<tr>

    <td> CategoryName</td>
    <td>
        <input type="hidden" id="hfCategoryID" value="-10" />
<input type="text" value="" id="txtCategory" class="form form-Control validate[required],ajax[ajaxUserCall]" />
   </td>
</tr>
<tr>

Web 服务器中的 Web 方法“CategoryViewService.asmx”:

[WebMethod]
public Class1 UserCheck(String fieldId, String fieldValue)
{
    String temp = fieldId;
    String temp2 = fieldValue;
    Class1 objInfo = new Class1();
    objInfo.FieldID = fieldId;
   if(//check UniqueValue in Database)
   {
   objInfo.Status = true;//Display Green Prompt
   objInfo.FieldValue = "All good1";
    }
    else
    {
    objInfo.Status = false; //Display Red Prompt
   objInfo.FieldValue = "Try Again!! not unique Value";
    }
    return objInfo;
     }

_ajax 在 jquery.validationEngine.js 中(由于我从 web 方法传递 xml(不是默认的 json),所以做了一点改变)

 _ajax: function(field, rules, i, options) {
         var errorSelector = rules[i + 1];
         var rule = options.allrules[errorSelector];
         var extraData = rule.extraData;
         var extraDataDynamic = rule.extraDataDynamic;
         if (typeof extraData === "object") {
            $.extend(data, extraData);
         } else if (typeof extraData === "string") {
            var tempData = extraData.split("&");
            for(var i = 0; i < tempData.length; i++) {
                var values = tempData[i].split("=");
                if (values[0] && values[0]) {
                    //var inputValue = field.closest("form, .validationEngineContainer").find(id).val();
                    data[values[0]] = values[1];
                }
            }
         }
         var data = JSON2.stringify({
             fieldId: field.attr("id"),
             fieldValue: field.val(),    
         });
         if (extraDataDynamic) {
             var tmpData = [];
             var domIds = String(extraDataDynamic).split(",");
             for (var i = 0; i < domIds.length; i++) {
                 var id = domIds[i];
                 if ($(id).length) {
                     var inputValue = field.closest("form, .validationEngineContainer").find(id).val();
                     var keyValue = id.replace('#', '') + '=' + escape(inputValue);
                     data[id.replace('#', '')] = inputValue;

                 }
             }

         }
         // If a field change event triggered this we want to clear the cache for this ID
         if (options.eventTrigger == "field") {
            delete(options.ajaxValidCache[field.attr("id")]);
         }
         // If there is an error or if the the field is already validated, do not re-execute AJAX
         if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) {
             $.ajax({
                 type: "post",
                 url: rule.url,
                 cache: false,
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 data: data,
                 field: field,
                 rule: rule,
                 async:true,
                 methods: methods,
                 options: options,
                 beforeSend: function() {},
                 error: function(data, transport) {
                     methods._ajaxError(data, transport);
                 },
                 success: function (xml) {
                             var json=xml.d
                            $('#ajaxStatus' + json.FieldID).val(json.Status);
                     // asynchronously called on success, data is the json answer from the server
                     var errorFieldId = json.FieldID;
                     //var errorField = $($("#" + errorFieldId)[0]);
                     var errorField = $("#"+ errorFieldId).eq(0);
                     // make sure we found the element
                     if (errorField.length == 1) {
                         var status = json.Status;
                         // read the optional msg from the server
                         var msg = json.FieldValue;

我还必须在 Web.Config 中添加它,因为它不断抛出错误

  <system.webServer>
 <handlers>
  <add name="ScriptHandlerFactory"
       verb="*" path="*.asmx"
       type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       resourceType="Unspecified" />
</handlers>

于 2016-12-28T00:05:06.063 回答