【问题标题】:$resource post json and retrieve json from/to mvc controller$resource 发布 json 并从/向 mvc 控制器检索 json
【发布时间】:2016-08-29 20:37:57
【问题描述】:

这是我的 AngularJs 代码:

var adminApp = angular.module('adminApp', ['ngResource']);

adminApp.controller('adminCtrl', function ($scope, AdminService) {
    AdminService.getRoles().$promise.then(function (rolesData) {
        //roles data empty is coming eventhough mvc controller returns something
    });
});

$scope.saveUser = function () {
    var userData = { "email": $scope.useremail, "role": $scope.selectedRole.name };
    AdminService.postUser({user: userData}).$promise.then(function () {
    });
}

服务代码

adminApp.factory('AdminService', function ($resource) {
    return $resource('', {}, {

        getRoles: {
            url: '/Admin/GetRoles',
            method: 'GET',
            isArray: true
        },
        postUser:{
            url: '/Admin/PostUser',
            method:"Post",
            isArray: true,
           params: {user: '@userData'}
        },

    });

});

用于发布和获取的 mvc 代码

public JsonResult GetRoles() {
    // data count is 2 here.that means some values there.
    return Json(data, JsonRequestbehavior.allowget);
}

public ActionResult PostUser(dynamic user)
{
    // user empty object coming here..
    return View();
}

任何人都为我提供了正确的解决方案,用于将 Json 发布到 mvc 控制器并使用 $resource 概念从 mvc 操作中检索 json。

【问题讨论】:

  • 你能把AdminService.getRoles()的结果输出到控制台($promise()之前)看看它返回了什么?
  • @OzW 我怎么能做到这一点?
  • adminApp.controller('adminCtrl', function ($scope, AdminService) { var result = AdminService.getRoles(); console.log(result); });
  • 您还可以查看 Chrome 开发者工具中的网络选项卡,以检查对“/Admin/GetRoles”的请求是否返回了您所期望的。另外,请注意.then() 方法接受另一个参数,即errorCallback。您可以利用它来检查服务器是否返回错误 (read more)。
  • @OzW 我正在获取值 rolesData 但当我在 mvc 中使用 jsonresult 时它返回空数组,如 [0]=[] 和 [1]=[]。我已经修改了内容结果,然后它正在工作

标签: c# angularjs json asp.net-mvc-5


【解决方案1】:

我已将 MVC 控制器返回类型从 Json 修改为 ContentResult。请在下面找到代码

public JsonResult GetRoles() {

     //data is string
    return new ContentResult{ Content= data, ContentType="application/json" };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多