2016-08-05 106 views
0

我有一個MVC 5正常應用程序。mvc 5驗證和更改DOM元素

在一個textbot用戶需要寫廣告用戶名(或者可能是「姓氏」)。我使用[Remote]批註,並在控制器上調用驗證功能。

進入驗證功能我做了一個LDAP查詢,如果我發現只有1個結果,我將驗證爲真,否則如果找不到任何結果或發現多於1個結果,則返回false。

直到這裏,沒有問題。

如果驗證沒問題,我會用確切的AD用戶名設置文本框的值(或者是一個隱藏的值)。

例如: 在我的域名中有用戶marco.rossi,並且是AD中唯一的Marco。 如果我在AD中搜索「Marco」,確認無誤。但是,當用戶提交時,我想通過域\ marco.rossi。

因此,我將設置爲一個隱藏或更好的文本框值從marco到域\ marco.rossi。

如何將文本框的值設置爲驗證函數?

預先感謝您。

+0

對於TextBox我的意思是

+0

UP,有沒有人知道如何做到這一點? –

回答

0

好的,經過大量的搜索,解決方案並不是最好的解決方案,但它的工作。

我看到這篇文章: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來獲取更多的數據,而不會丟失驗證機制。但我找不到方法。