将下拉列表选项传递给控制器

时间:2015-12-07 08:14:11

标签: html model-view-controller

我有一个select标签形式的下拉列表,如下所示:

<select id = "1">
<option>Amy</option>
<option>Gi-Anne</option>
</select>

我想将选定的选项--Amy或Gi Anne传递给控制器​​的这个方法。

public String name (string nameSelected)
{
    var query = new NameQuery();
    if(nameSelected.Equals('Amy')) 
    {run a specific query}
else if(nameSelected.Equals('Gi-Anne')) 
        {run a specific query}

}

如何将所选下拉列表值的参数传递给控制器​​?感谢您的帮助,并提前致谢。

1 个答案:

答案 0 :(得分:0)

使用AngularJS“相当”容易,请参阅此Plunk了解(模拟)示例。

HTML更改为:

<body ng-app="myApp">
<div ng-controller="myController">
  State: {{onChangeText}}
  <br/>
  <select ng-model="selectedItemId" id="itemList" ng-change="onChange()">
    <option value="{{item.id}}" ng-selected="{{item.id == selectedItemId}}" ng-repeat="item in items">{{item.name}}</option>
  </select>
  <br/>
  {{selectedQuery}}
</div>
</body>

使用这样的控制器:

app.controller("myController", [
      "$scope",
      "$http",
      function($scope, $http){
        var self = {};

        self.simulatedGetQuery = function() {
          console.log($scope.selectedItemId);
          $scope.selectedQuery = "";

          switch($scope.selectedItemId) {
            case "1":
              $scope.selectedQuery = "Query Amy";
              break;
            case "2":
              $scope.selectedQuery = "Query Gi-Anne";
              break;
          }
        };

        self.httpGetQuery = function() {
          $http({
            method: 'GET',
            url: 'http://somehostname/action/' + $scope.selectedItemId
          }).then(function successCallback(response) {
            $scope.selectedQuery = response;
          }, function errorCallback(response) {
          });
        };

        // -- SCOPED -- //

        $scope.selectedItemId = 0;

        $scope.items = [
          {
          "id": 1,
          "name": "Amy"
          },
          {
          "id": 2,
          "name": "Gi-Anne"
          }
        ];

        $scope.onChange = function() {
          $scope.onChangeText = "simulated GET triggered.";

          self.simulatedGetQuery();

          // Use this for actual GET
          // self.httpGetQuery
        };


        // --- //

        $scope.onChangeText = "waiting for user input";
        $scope.selectedQuery = "no query selected. Chose a person for a valid query.";
      }]);

它需要在真实环境中充实,但我认为它可以用于模拟测试。查看Plunk中的脚本,了解有关如何执行此操作的更详细信息。所有这些都是客户端。

$http调用的URL将是您的后端(MVC或Web API)控制器。