asp.net web api - How to return data from web api controller using angularjs?

Hi I am developing one web api with angularjs application. I am doing file upload module. I am facing problem in returning object once file upload is finished.

Below is my api code to save file related data to database and if it is succsfull I am returning object.

NCT_FileUpload obj = new NCT_FileUpload();
obj.file_path = uploadPath;
obj.user_id =9;

entityObject.NCT_FileUpload.Add(obj);
int result = entityObject.SaveChanges();
if (result == 1)
{
    return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
}
else
{
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "1");
}

This is my angularjs code.

$scope.uploadFiles = function () {
    $scope.uploading = true;
    uploadService.uploadFiles($scope)
        // then() called when uploadFiles gets back
        .then(function (data) {
            // promise fulfilled
            $scope.uploading = false;
            if (data === '') {
                alert("Done!!!")
                $scope.formdata = new FormData();
                $scope.data = [];
                $scope.countFiles = '';
                $scope.$apply;
            } else {
                alert("Shit, What happended up there!!! " + data);
            }
        }, function (error) {
            $scope.uploading = false;
            //Server Error
            alert("Shit2, What happended up there!!! " + error);
        }
    );
};

Below is my service code in angularjs

if (typeof response.data === 'string') {
    return response.data;
} else {
    return $q.reject(response.data);
}

Here i want to check with object and not as string.

I am able to save data in server, If i put below code in api controller i am able to display done. But i am returning object so my data will not be empty. Currently my error function is executing. I want to handle object returned from api in success function. Is there any way to do this? Any help would be appreciated. Thank you.

 return new HttpResponseMessage(HttpStatusCode.OK) ;

1 Answer

  1. Mars- Reply

    2019-11-14

    I think the problem here is the generic parameter. Change this:

    return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
    

    To this:

    return Request.CreateResponse(HttpStatusCode.OK, obj);
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>