如何填充@Html.当我们从@Html.DropdownListfor中选择一个值时

How to populate @Html.Textboxfor when we select a value from @Html.DropdownListfor

本文关键字:@Html 选择 一个 我们 何填充 填充 DropdownListfor      更新时间:2023-09-26

如何将数据填充到@Html中。当我们在@Html中选择值时使用的文本框。下拉列表在ASP。NET MVC5应用。这是更好的方式来填充数据在文本框中使用脚本或有任何其他的方法来做,如果可能的话,给我一个例子。

我是这样做的。使用JavaScript。您应该编写一个脚本,其中所有ajax调用都来自单个入口点。它更容易重用、维护和调试。请记住,这段代码只是一个大纲,您必须对其进行清理。不要像建议的那样访问服务器,并在每次下拉列表值更改时更新视图模型。这太荒谬了。我会告诉你我对这种情况的全部看法。只需从XMLHttpRequest中拉入视图模型,无论你喜欢什么,并在每次下拉列表更改时过滤当前数据。

步骤1:为视图模型向控制器发出请求

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

step2:获取ViewModel并将其存储在对象或变量中

    //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;      
    }

试试这样。

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