我创建了一个aspx表单。我正在使用JQuery验证引擎(http://www.position-relative.net/creation/formValidator/)进行验证。
现在,我想通知用户数据库中已使用的id是否已存在,并且具有相同的红色气球错误提示(jquery验证引擎的默认值)。
我搜索谷歌并获得了一些提示,但我对如何将参数传递给ajaxcall中涉及的web方法感到困惑。
这是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。
答案 0 :(得分:0)
可以使用此article
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;
}
在
背后的代码中创建了一个web方法[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" />
答案 1 :(得分:0)
我正在使用内联表单验证引擎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方法&#34; CategoryViewService.asmx&#34;在网络服务器中:
[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>