如何将对象发布到的WebAPI [英] How to post an object to WebAPI

查看:125
本文介绍了如何将对象发布到的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何从我的形式发布一个对象的Web API服务。在我的控制,我定义,我想输入值添加到模型。

I'm trying to figure out how to post an object from my form to a web api service. Within my controller I defined a model that I wanted to add input values to.

$scope.Label;

我的输入字段中的我有他们使用的约束 NG-模型如:

<input type="checkbox" ng-model="label.isPublic" />
<input type="text" ng-model="label.labelName" required focus-me />

在表单提交这两个字段一个传递给我的服务并提交给我的WebAPI的

On the submission of the form these two fields a passed to my service and submitted to my WebApi

我已经尝试了本提交有两种方式:

I have tried this submission in two ways:

function addLabel(label) {
        var mylabel = encodeURIComponent(angular.toJson(label));
        return $http.post('reportLibrary/createlabel/', { params: label }, {

        }).then(function (response) {
            return response.data;
        });
    };

和作为也没有声明参数以下

and also as the following without declaring parameters

function addLabel(label) {
        var mylabel = encodeURIComponent(angular.toJson(label));
        return $http.post('reportLibrary/createlabel/', label , {

        }).then(function (response) {
            return response.data;
        });
    };

在的WebAPI我有一个方法设置该职位

In the webAPI I have a method setup for the post

 [Route ("reportLibrary/createlabel/")]
        [HttpPost]
        public DTOs.ReportLabel CreateLabel(DTOs.ReportLabel json)
        {
            DTOs.ReportLabel result = new DTOs.ReportLabel();

        //.... do stuff
            return result;
        }

的ReportLabel(DTO)的定义如下:

The ReportLabel (dto) is defined as follows:

public class ReportLabel
{
    public Int64 LabelId { get; set; }
    public string LabelName { get; set; }
    public bool IsPublic { get; set; }
    public IEnumerable<Report> Reports { get; set; }//placeholder?

}

我的问题是,当我从我的角度后期服务对象就会出现在API中为空。如果我改变了方法的类型有点像JToken或JObject值显示。

The issue I have is when I post an object from my angular service it shows up as null within the API. If I change the type in the method to something like a JToken or JObject the values appear.

谁能帮我明白为什么当我定义它不是从整个角度传递的类型?

Can anyone help me understand why when I define the type that it is not passed across from angular?

感谢

推荐答案

好像你可能会做一个额外的步骤。你并不需要连接code以JSON然后通过在JSON

It seems like you may be doing an extra step. You don't need to encode in json then pass in in json

return $http.post('reportLibrary/createlabel/', { LabelId: 101, LabelName: 'myname' }, {

然后

 public DTOs.ReportLabel CreateLabel([FromBody]ReportLabel reportLabel)

看看网络价值将会由您应该在调试工具看到或招潮蟹实际值公布(表值)。

Take a look at the network values going by and you should see in debug tools or fiddler the actual posted values (form values).

这篇关于如何将对象发布到的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆