Error calling webmethod

Asked

Viewed 73 times

1

I’m creating a webmetod that will make the autocomplete of some fields on my screen, however I’m getting error 500


        <System.Web.Services.WebMethod>
    <System.Web.Script.Services.ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False)>
            Public Function AutoComplete(ByVal prefixText As String) As String
                Dim resposta As string =  "funciona"


                Return Newtonsoft.Json.JsonConvert.SerializeObject(resposta)
            End Function

as you can see it is quite simple just to see if it returns the server message

My javascript

function buscaPorParametro(campo) {
            var valorDigitado = $("input[name='" + campo +"']")
            console.log(txtBox.val())
            $.ajax({
                data: JSON.stringify("{  prefixText: '" + valorDigitado.val() + "' }"),
                dataType: "json",
                url: url,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: OnSuccess,
                error: onError
            });
        }
        function OnSuccess(data) {


        }
        function onError(err) {
            console.log(err);
            $('#LoadingPanel').css('display', 'none');
        }

error returned from server

"{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":"   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}"

someone would tell me where I’m going wrong?

Thank you

2 answers

0

As in your signature Webservice you expect only one string, is exactly what you should go through when consuming it via javascript.

When sending data via javascript thus:

JSON.stringify("{  prefixText: '" + valorDigitado.val() + "' }")

The value will be converted into something like this:

var dictionary = new Dictionary<string, object>();
dictionary.Add("prefixText","xpto");

And when trying to consume your Webservice, there will be conversion error as a IDictionary cannot be converted to string.

I suggest you change your Webservice subscription to that:

Public Function AutoComplete(ByVal dados As Dictionary<string, Object>) As String

Or just send one string via javascript.

  • Bruno talks, man I tried to do this way ... and it didn’t work, he says that because Dictionary is an implementation of the Idictionary interface he can’t convert the object, you managed to run the code like this ???

  • Oops, I forgot the first Dictionary constructor parameter. I edited the answer... give a look

  • then I had already noticed that, even doing as it should, the error appears at the moment of climbing the application. The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, Publickeytoken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, Publickeytoken=b77a5c561934e089]] is not supported because it Implements Idictionary. I think the only way to make it work is by typing an object and putting it in the method signature ... probably this will solve

  • Put string on your webservice and try to send it just like this: valueDigited.val()

  • I did otherwise look at the answer, []’s

0

In the end I managed to solve the problem by typing the method signature

 Public Function AutoCompleteCodigo(ByVal _getDados As Dados) As String

End Function

and in javascript

function buscaPorParametro(campo) {            
        var dados = {};
        dados._getDados = {};
        dados._getDados.Descricao = $(this).attr("Descricao");
        $.ajax({ data: JSON.stringify(dados),
            dataType: "json",
            url: url,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: onError
        });
    }
    function OnSuccess(data) {

        alert('good');
    }
    function onError(err) {
        console.log(err);
        $('#LoadingPanel').css('display', 'none');
    }

where the variables below are the construction of the object being sent to the webmethod

var dados = {};

data. _getDados = {};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.