好的,經過大量的搜索,解決方案並不是最好的解決方案,但它的工作。
我看到這篇文章:http://www.garethelms.org/2011/01/asp-net-mvc-remote-validation-what-about-success-messages/
加雷建議修改jquery.validate.js
後的「黑客」,爲每個遠程驗證,被稱爲是有一個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請求封裝到500ms後觸發的計時器中,因爲我注意到som當在文本框上寫入時,遠程驗證也會開始。 因此,對於每個字符的異步驗證開始,但是當驗證返回正常時,提交按鈕將被禁用,500毫秒後第二個請求開始並更改用戶名稱。每個新角色都會重置定時器,因此只有最後一個角色纔會觸發第二個ajax。
最後... 2 ajax不是最好的場景,但我真的試圖使用JsonResult來獲取更多的數據,而不會丟失驗證機制。但我找不到方法。
對於TextBox我的意思是 –
UP,有沒有人知道如何做到這一點? –