Lucas Baumgart
Lucas Baumgart

Reputation: 41

$http request with angularjs is returning my html doc

I'm new here, so sorry if I'm making some mistake with the post...

I'm trying to use angularjs with ASP.NET Web Forms, and everything was going well until I need to make a request to the c# webmethods. I searched here and on other pages for the solution and didnt found anything.

Let's go to te problem: My request just return my Default.aspx html code, and not my JSON. In fact, my request doesn't call my webmethod...

app.controller('CtrlBoletos',function($scope, FactoryBoleto) {

    $scope.selections = [];

    $scope.boletos =  FactoryBoleto.getBoletos();

    $scope.gridBoletos = {
        data: 'boletos',
        selectedItems: $scope.selections,
        multiSelect: false
    };
});


app.factory('FactoryBoleto', function ($http) {

   var getBoletos = function() {

        $http({
           method: 'POST',
           url: "./Default.aspx/get_boleto",
           async: false
        }).success(function(result){
           console.info(result);
        });
   };
   return { getBoletos: getBoletos };
});

and this is my webmethod

[WebMethod]
 public static string get_boleto()
{     
    List<TFechamento_Boleto> lista = new List<TFechamento_Boleto>();
    JavaScriptSerializer serializer =new JavaScriptSerializer();
    TFechamento fechamento = new TFechamento(2);
    lista = fechamento.getDados(1).Boleto;

    var json = serializer.Serialize(lista);
    return json;

}

Ah, and if i make the request with JQuery AJAX I get the json...

someone help me, im getting crazy with this... and sorry for my bad english :p

Upvotes: 4

Views: 2241

Answers (4)

salimido
salimido

Reputation: 151

i have the same problem as you.until now i have create an alternative solution to get json result from my c# webmethod:

 $scope.yourscopefunction=function(){
         $.ajax({
                        type: "POST",
                        url: "webmethodURL",                       
                        contentType: "application/json;charset=utf-8",
                        success: function (data) {

                            $.map(data.d, function (dataobject) {

                              alert(dataobject.yourobjectfield);

                            });

                        },
                        error: function (xhr, status, errorThrown) {

                            alert(status + "* " + errorThrown + " * " + xhr);
                        }
                    });

 };

if you have an other solution better than this using $http, please tell me

Upvotes: 0

AxL
AxL

Reputation: 11

I've resolved this issue by setting headers, responseType and by adding an empty data object

factory.handshake = function () {
    return $http({
        method: "POST",
        url: urlBase.concat("/Handshake"),
        data: {},
        headers: { "Content-Type": "application/json" },
        responseType: 'json'
    });
};

...and, when I call my webmethod the result magically appears

    myFactory.handshake()
        .success(function (fromApi) {
            alert(fromApi.d);
        })
        .error(function (error) {
            $scope.status = 'Unable to load sport data: ' + error.message;
        });

Upvotes: 1

EdSF
EdSF

Reputation: 12351

I tinkered with this out of curiosity/learning Angular:

The issue is content-type header - if you don't define this, the WebMethod isn't invoked and you will get the aspx page (in both jQuery and Angular..any actually)

ASP.NET AJAX Content-Type Header Validation

There is a built-in validation layer of protection that ASP.NET enforces for both GET and POST based ASP.NET AJAX web methods, which is that regardless of the HTTP verb being used, ASP.NET always requires that the HTTP Content-Type header is set to the value application/json. If this content type header is not sent, ASP.NET AJAX will reject the request on the server.

So try this, not really sending any data, but Angular will set the header:

$http.post("default.aspx/get_boleto", {});

or in your case:

 $http({
       method: 'POST',
       url: "./Default.aspx/get_boleto",
       data: {}, //nothing really, just doing this so the header is set
       async: false
    }).success(.....

If you inspect your XHR call:

Angular XHR without data, Content-Type isn't set:

POST /default.aspx/helloWorld HTTP/1.1
Host: localhost:51120
Connection: keep-alive
Content-Length: 0
Cache-Control: max-age=0
Accept: application/json, text/plain, */*
Origin: http://localhost:51120
User-Agent: ....
Referer: ....
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

Angular XHR with data, Content-Type is set:

POST /default.aspx/helloWorld HTTP/1.1
Host: localhost:51120
Connection: keep-alive
Content-Length: 2
Cache-Control: max-age=0
Accept: application/json, text/plain, */*
Origin: http://localhost:51120
User-Agent:...
Content-Type: application/json;charset=UTF-8
Referer: ....
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

New at Angular so if there are better/easier ways, I'll defer...

Hth...

Upvotes: 0

Braulio
Braulio

Reputation: 1728

Are you missing [ScriptMethod(UseHttpGet = true)] ?

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public List<ProjectOfEmployee> GetAllProjectName()
{
   return GetProjectName();   
}

http://shahjadatalukdar.wordpress.com/2013/08/09/how-to-call-asmx-webservice-using-http-get- with-jquery-ajax/

Checking, some others threads:

https://groups.google.com/forum/#!msg/angular/AQ_caU-qVJ0/Csugs6zI2-EJ

AngularJS call webmethod

Upvotes: 0

Related Questions