2016-11-08 37 views
-1

中選擇一個值時,如何填充@ Html.Textboxfor當我們在ASP.NET MVC5應用程序的@ Html.DropdownListfor中選擇值時,如何將數據填充到@ Html.Textboxfor中。哪種方法可以更好地通過使用腳本來在文本框中填充數據,或者如果可能的話,還有其他方法可以提供示例。當我們從@ Html.DropdownListfor

+0

@ user3608792您希望每次有人更改下拉列表值時,他都會點擊服務器? –

+0

當我們在下拉列表中選擇值時,我已經通過數據庫獲取了值到文本框中 –

回答

0

這就是我會這樣做的。使用JavaScript。你應該製作一個腳本,你所有的ajax調用都來自一個入口點。重用,維護和調試更容易。請記住,這段代碼只是一個大綱,你將不得不清理它。不要按建議點擊服務器,並在每次下拉列表值更改時更新您的視圖模型。這太可笑了。我會全力爲您解決這個問題。只需從XMLHttpRequest中拉入視圖模型即可,並且每次更改下拉列表時都會過濾當前的數據。

第1步:對您的控制器請求視圖模型

//quick example 
var xhr = new XMLHttpRequest(); 
xhr.open('GET', 'Controller/Methodname'); 
xhr.send(null); 

第二步:獲取視圖模型並將其存儲在一個對象或變量或W/E你想

//handle the call 
    xhr.onreadystatechange = function() { 
     var DONE = 4; // readyState 4 means the request is done. 
     var OK = 200; // status 200 is a successful return. 
     if (xhr.readyState === DONE) { 
     if (xhr.status === OK) 
      ...xhr.responseText // 'This is the returned text. so store it somewhere' 
     } else { 
      console.log('Error: ' + xhr.status); // An error occurred during the request. 
     } 
     } 
    }; 

第3步:爲下拉列表添加onChange事件。

onDropdownChange() { 
     // based on what is selected, filter you data and populate the textbox 
     document.getElementById("YourTextboxID").value = your value;  
    } 
+0

我可以寫javascript(不是上面的例子)並在MVC5中執行它。 iF可能建議我解決方案 –

+0

@addadaSatish你是什麼意思在MVC5中執行它? MVC是一種設計模式。請解釋你的意思。 –

+0

對不起,我認爲我誤刪了這個。 –

-1

嘗試類似這樣的東西。

function ondropdownchange(){ 
    $.get("yourmethodurl", function(data, status){ 
     $('#yourtextbox').val(data); 
    }); 
} 
+0

您完全沒有回答他的問題'通過使用腳本來填充文本框中的數據是更好的方法,還是有其他方法可行,如果可以的話,給我一個例子。 –