【问题标题】:How to pass object to angularjs controller using MVC controller Action如何使用 MVC 控制器动作将对象传递给 angularjs 控制器
【发布时间】:2015-10-15 10:40:18
【问题描述】:

我想使用 MVC 控制器动作将对象发送到 angularjs 控制器,这可能吗?

假设

 public ActionResult Dashboard()
    {
        return View();
    }

我想将对象传递给 app.js 怎么做

【问题讨论】:

  • 更具体。同时发布代码。
  • MVC Controller Action 你的意思是来自Spring 控制器?
  • 没有来自 Asp.net MVC 控制器动作意味着返回 view() 我想将数据传递给 angularjs 控制器我想知道它是否可能

标签: angularjs model-view-controller


【解决方案1】:

您的问题有点模糊,您需要更具体地说明您要做什么。

一般来说,这就是你在 Angular 中从 MVC 应用程序获取数据的方式。

在 MVC/WebAPI 的情况下,您应该使用操作将 JSON 结果返回给 Angular 服务,然后由 Angular 处理。 下面的例子:

  app.factory('myService', function($http) {
  var myService = {
    GetData: function() {
      // $http returns a promise, which has a then function, which also returns a promise
      var promise = $http.get('<ActionURL>').then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  // Call the async method and then do stuff with what is returned inside our own then function
  myService.GetData().then(function(d) {
    $scope.data = d;
  });
});

从 MainCtrl 调用此服务后,Angular 将在其 $scope.data 变量中提供来自 MVC 操作的数据。

【讨论】:

  • 这是首选方法。也可以将模型反序列化为 json,从而节省到服务器的行程
  • @JeffDunlop:你是什么意思?无法从评论中想象你的意思。有样品吗?
猜你喜欢
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多