-1

I am trying to bind Drop down from services. But success event is not hitting.

Science I have total 5000 records so in

web.config file I have added Binding May be due to this region I am getting "Internal server Error" ? I am not sure about this Please guide me where I am doing wrong

AJAX

var AllProduct = [];
        function GetAllProduct() {
            var params = { DivisionCode: $('#ddlDivision').val() };
            $.ajax({
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(params),
                url: 'Header.aspx/GetProduct',
                dataType: 'json',
                async: false,
                success: function (res) {
                    Product(res.d)
                    OnSuccessProductCall();

                }
            });
            function Product(pdata) {
                AllProduct = pdata;
            }
        }
        function OnSuccessProductCall(data, status) {
            result = AllProduct;
            $("[id$='ddlProduct']").append($("<option>").val("0").text("Select"));
            if (result != undefined && result.length > 0) {
                for (i = 0; i < result.length; i++) {
                    $("[id$='ddlProduct']").append($("<option>").val($.trim(result[i].BU_CAT_CODE)).text($.trim(result[i].BU_CAT_DESC)));
                }
            }
        }

Services

While debugging I can see my services returning Collection of data But not able to hit Success Event

 [WebMethod]
        public static ServiceReference1.PRODUCT[] GetProduct(string DivisionCode)
        {
            ServiceReference1.MasterDataServiceClient oClient = new ServiceReference1.MasterDataServiceClient();
            ServiceReference1.PRODUCT[] prod = oClient.GetProducts(DivisionCode, null, null, null, null, null, null, null);
            return prod;
        }

Web.Cofig

<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="basicHttp" allowCookies="true"
             maxReceivedMessageSize="20000000"
             maxBufferPoolSize="20000000">
          <readerQuotas maxDepth="32"
               maxArrayLength="200000000"
               maxStringContentLength="200000000"/>
        </binding>
        <binding name="WSHttpBinding_IMasterDataService" />
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://almhosrwfebpm01.almaraigroup.local:8524/AlmaraiDataService.svc" binding="wsHttpBinding" bindingConfiguration="basicHttp" contract="ServiceReference1.IMasterDataService" name="WSHttpBinding_IMasterDataService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>

My data type is JSON

Sample data Coming from Web Services.

enter image description here Where I am doing wrong.

Error Message

 {"Message":"An attempt was made to call the method \u0027GetProduct\u0027 using a POST request, which is not allowed.","StackTrace":"   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"}

enter image description here

  • 3
    add `error: function (request, status, error) { alert(request.responseText); }` after success and lets see what going on. – Pakawat Smutkun Oct 16 '20 at 07:07
  • As above, also check the browser network tab to see exactly what's being returned via your ajax call – freedomn-m Oct 16 '20 at 07:19
  • I am getting this message {"Message":"An attempt was made to call the method \u0027GetProduct\u0027 using a GET request, which is not allowed.","StackTrace":" 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"} – user14304386 Oct 16 '20 at 07:21
  • @freedomn-m as I can see network tab nothing is visible – user14304386 Oct 16 '20 at 07:29
  • @PakawatSmutkun I have posted In comment section message on Error Event – user14304386 Oct 16 '20 at 07:30
  • do you get any error in browser console? – Alireza Madad Oct 16 '20 at 07:34
  • did you get any alert after adding Pakawat Smutkun sample code? – Alireza Madad Oct 16 '20 at 07:35
  • but my guess is this line type: 'GET', in ajax call changet to type: 'POST' @user14304386 – Alireza Madad Oct 16 '20 at 07:36
  • @AlirezaMadad yes I have posted Error Message in Comment section. I have Change from GET to POST. But again its showing error Like {"Message":"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.","StackTrace":" – user14304386 Oct 16 '20 at 07:37
  • @AlirezaMadad I have changed from GET to POST But still error. Not hitting on success Event – user14304386 Oct 16 '20 at 07:47

3 Answers3

0

Add this instead of [WebMethod]

[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
 public static ServiceReference1.PRODUCT[] GetProduct(string DivisionCode)
        {
            ServiceReference1.MasterDataServiceClient oClient = new ServiceReference1.MasterDataServiceClient();
            ServiceReference1.PRODUCT[] prod = oClient.GetProducts(DivisionCode, null, null, null, null, null, null, null);
            return prod;
        }

An attempt was made to call the method \u0027GetNextImage\u0027 using a GET request, which is not allowed

0

change the " data: JSON.stringify(params)," Try this:

data: "{obj:" + JSON.stringify(params ) + "}",

In the web method: 1-change the return type to void. 2-Add this code :

JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(prod));

this article should help: https://www.c-sharpcorner.com/blogs/how-to-retrieve-data-using-ajax-in-asp-net

  • I have Replace data: "{obj:" + JSON.stringify(params ) + "}", But still not hitting Sucess Event As error I am getting like this: {"Message":"An attempt was made to call the method \u0027GetProduct\u0027 using a POST request, which is not allowed.","StackTrace":" 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"} – user14304386 Oct 16 '20 at 07:52
0

Well, Technically, you must always include an error event so you know when an ajax call fails and handle it accordingly. It is clearly a bad practice to ignore it.

Secondly, as far as I know, a WebMethod doesn't allow a GET request, you must use a POST request so it responds back and sends the data without error, or if you strictly want to use WebMethod in a GET request then you should decorate your WebMethod with this attribute: [ScriptMethod (UseHttpGet = true)]

Here is the refined ajax call, Try this and see what error pops up and try to resolve it again.

var AllProduct = [];
function GetAllProduct() {
    var params = { DivisionCode: $('#ddlDivision').val() };
    $.ajax({
            type: 'POST', // Modified this to a POST call
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(params),
            url: 'Header.aspx/GetProduct',
            dataType: 'json',
            async: false,
            success: function (res) {
                Product(res.d)
                OnSuccessProductCall();
            },
            error: function(err) { // Added this event to capture the failed requests.
                console.log(err);
            }
   }); 
   // ... Your Further Code ...
}
Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42