好的,经过大量搜索,该解决方案不是最好的解决方案,但它正在工作。
我读了这篇文章:http://www.garethelms.org/2011/01/asp-net-mvc-remote-validation-what-about-success-messages/
Gareth 建议修改 jquery.validate.js
在“hack”之后,对于每个 REMOTE 验证,调用一个具有 {Action name}_response 名称的 javascript 函数。
所以对于这个:
[Required]
[Remote("CheckADUserValidation", "CONTROLLER")]
public virtual string ad_username { get; set; }
我提供了这个函数:(在视图的脚本部分)
function CheckADUserValidation_response(bIsValid, aErrors, oValidator)
{
// I disable immediatly the submit button to wait the right username
// so, also if validation is ok, I cannot submit until the right value is on the ad_username textbox
$('#btnSubmit').attr('disabled', 'disabled');
if (bIsValid == true) {
// after I call an Ajax on an Action, that instead of giving me true or error messages, give me the username
$.ajax({
type: "GET",
dataType: 'json',
url: '/CONTROLLER/ActionToHaveUsername/',
contentType: 'application/json;charset=UTF-8;',
async: true,
data: 'ad_username=' + $('#ad_username').val(),
success: function (response) {
if (response != '') {
// Ok there is the response
$('#ad_username').val(response);
$('#btnSubmit').removeAttr('disabled');
return true;
} else {
$('#btnSubmit').attr('disabled', 'disabled');
return false;
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (jqXHR, textStatus) {
}
});
} else {
return false;
}
}
这是在控制器上调用的动作:
public JsonResult ActionToHaveUsername(string ad_username)
{
string tmpADName;
JsonResult tmpResult = new JsonResult();
// this function make the dirty work to take in input a name and search for unique ActiveDirectory Username, and return me in tmpADNName
AppGlobals.functions.CheckADUserValidation(ad_username, out tmpADName);
tmpResult.Data = tmpADName;
tmpResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return tmpResult;
}
最好的结果是将 ajax 请求封装到一个 500 毫秒后触发的计时器中,因为我注意到有时远程验证也会在文本框上写入时开始。
因此,对于每个字符,异步验证开始,但是当验证返回正常时,提交按钮被禁用,并且在 500 毫秒后第二个请求开始并更改用户名的名称。每个新角色都会重置计时器,因此只有最后一个角色会真正触发第二个 ajax。
最后... 2 ajax 不是最好的方案,但我确实尝试使用 JsonResult 来获得更多数据作为回报,而不会丢失验证机制。但我没有找到办法。