Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

javascript - How to post an object to WebAPI

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;

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 />

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;
        });
    };

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;
        }

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?

}

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?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' }, {

then

 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...