c# - 从 AngularJS 和 ASP.net MVC 传递数据 $http.post 获取 null

标签 c# asp.net-mvc angularjs angularjs-directive angularjs-controller

我正在尝试将数据从 AngularJS 传递到 ASP.net MVC,但始终为空。 这是我的代码(只发布基本的、按钮、 Controller 和 C#:

HTML:

<a class="btn btn-grey btn-lg btn-block" ng-click="AddCar()">Save</a>

Controller

$scope.AddCar = function () {
            $http.post("Cars/AddCar", JSON.stringify($scope.new.JsonCar)).success(function (data) {
                Alert(ok)
            })

c#

public string AddCar(string JsonCar) 
        {
            try
           ....
        }

在 JSON.stringify($scope.new.JsonCar) 我得到这个:

"{"Name":"FIAT 500","Description":"New car","MaxUserCapacity":5,"PhotoPath":"none"}"

我做错了什么?

最佳答案

将您的对象直接作为对象传递,而不是将其字符串化。由于它现在正在传递,因此它是一个字符串,而不是可以正确反序列化的对象。

$http.post("Cars/AddCar", $scope.new.JsonCar).success(function (data) {
            Alert(ok)
        })

创建一个与您的负载相匹配的 Car 对象。序列化程序将为您处理您的 JSON 对象。

public Car AddCar(Car car) 
    {
        try
       ....
    }

我的假设是,在某些时候,您无论如何都会将字符串反序列化为一个对象。这只是为您节省了额外的步骤。

关于c# - 从 AngularJS 和 ASP.net MVC 传递数据 $http.post 获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465390/

相关文章:

c# - 为什么在 C# 中使用 "where T: struct"作为通用枚举扩展方法?

c# - 无法将类型 System.web.mvc.JsonResult 隐式转换为 System.Generic.IEnumerable

c# - MVC 路由参数为空

javascript - Angular 2 "this"无法访问嵌套函数中的全局变量

angularjs - Bower:无法找到适合 Angular 的版本

c# - 在 LINQ 中查询子集合

c# - ASCIIEncoding 在 Windows 8 Store 应用程序中不支持

c# - 如何生成 .svc 文件?

asp.net-mvc - Web Api 过滤器 - 检查装饰器是否存在

html - 我的侧边栏滚动条不工作