How to call a non-stationary method from AJAX?

Here is my code I'm calling from AJAX ...

[WebMethod] [ScriptMethod] public static string save(string parameter) { country_master obj_country = new country_master(); obj_country.Country_Name = Page.Request.Params["name"].ToString().Trim(); obj_country.saved(); return ""; } 

Here I can not access the parameters passed from the page through Page.Request.

 string name = HttpContext.Current.Request.QueryString["name"].Trim(); return "error"; 

after writing the first line, the return statement returns no AJAX. Please help me how to do this. Thanks...

+4
source share
2 answers

To get the current context, you can use HttpContext.Current , which is a static property.

After that, you can access things like a session or profile and get information about the state of the site.

HttpContext.Current.Session etc.

This link may help you: Server side calls through AJAX without a static method

The reason that the web method should be static is to avoid accessing the controls on the instance page.

+5
source

Yo can use the static class HttpContext.Current , however you can skip this if you declare the parameters you want to use on your method and just pass the parameters using your AJAX call

You must pass the parameters directly to the method.

I have some working examples in my Github repository , feel free to browse the code.

The PageMethod method is called as a summary:

Note: how the AJAX is used jobID jobID jobID parameter is passed along with the request and how it is used inside the transparent PageMethod

AJAX call

  $.ajax({ type: 'POST', url: '<%: this.ResolveClientUrl("~/Topics/JQuery/Ajax/PageMethods_JQueryAJAX.aspx/GetEmployees") %>', contentType: 'application/json; charset=utf-8', dataType: 'json', data: '{"jobID" : ' + jobID +'}', async: false, cache: false, success: function (data) { $('#employees').find('option').remove(); $.each(data.d, function (i, item) { $('<option />').val(item.EmployeeID).text(item.FirstName).appendTo('#employees'); }); }, error: function (xhr) { alert(xhr.responseText); } }); 

Page Method

  [WebMethod] public static List<EmployeeModel> GetEmployees(int jobID) { var ctx = new PubsDataContext(); return (from e in ctx.employee where e.job_id == jobID orderby e.fname select new EmployeeModel { EmployeeID = e.emp_id, FirstName = e.fname }).ToList(); } 
0
source

Source: https://habr.com/ru/post/1434129/


All Articles