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

查看:35
本文介绍了如何将对象发布到 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-model 绑定它们,例如:

within my input fields I have them bound using ng-model such as:

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

在提交表单时,这两个字段a传递给我的服务并提交给我的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;
        });
    };

还有如下不声明参数

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?

}

我遇到的问题是,当我从 angular 服务发布对象时,它在 API 中显示为 null.如果我将方法中的类型更改为 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.

谁能帮我理解为什么当我定义它不是从 angular 传递的类型时?

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

谢谢

推荐答案

看来您可能要执行额外的步骤.你不需要在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天全站免登陆