Asp Net Jquery Ajax Example

Posted on  by admin

Modified7 years, 11 months ago.

(Question resolved with the help of the two reply posts--see below). I would appreciate help getting a simple example of exchanging data JSON data between a browser (using JavaScript/JQuery) and ASP.NET (using Visual Studio 2010). When I click a button the following is executed:.

In Visual Studio, I have the following code associated with an ashx file. When I run it and click the button, everything works as expected except I don't see myData passed to the C# code--I am looking at context.Request.QueryString in the debugger and it shows "{}".

I have seen examples using. but Visual Studio "Request" does not seem to be defined. All I want to do is see data move both ways, and I appear to be half way there.

Any help would be appreciated. * RESOLVEDFirst, if you want to send some form parameters from JavaScript to ASP.NET one should use the ajax call in the second post below and do NOT use stringify on the data. In other words, if don't specify the data being sent is json the lack of any specification defaults to 'application/x-www-form-urlencoded').

This will causes the object's fields to be appended in a "url" format (field=X&field2=Y&field3=Z.) and thus shows up in ASP.NET using Request.Form["field"].

Second, if you really do want to send JSON data, then specify this type is what is being sent (like I have done above) and use the InputStream on the receiving side.
Further parsing of the received string is then required to get at the field values.
In my example, I am sending back JSON data having "manually" encoded it into a string.
I believe there is a JSON serialization routine so that C# objects can be sent over.
236236 bronze badges. Other resource suggest removing the contentType: 'application/json; charset=utf-8', from the AJAX call:.
Read the values on the server side:. You can also try:. which was mentioned here:
44 gold badges3737 silver badges6363 bronze badges. 6363 bronze badges. I got this working right away.

This is its most basic form:. 236236 bronze badges. 16.8k88 gold badges5151 silver badges7474 bronze badges. 5151 silver badges7474 bronze badges. Overview: Here in this article will see jQuery Ajax JSON example, i.e.

calling jQuery Ajax WebMethod and get JSON format result (JSON data) in C# Webform.
In short a simple jQuery Ajax JSON example in C# with MS SQL Server database.
If you are looking for how to get JSON formatted results from jquery ajax call in C#, then this post will explain step by step process.
You can also check 3 ways to convert DataTable into JSON Stringin C#.
AJAX stands for Asynchronous JavaScript and XML and using ajax we load data from the server without reloading the whole web page refresh.
i.e we can update a specific part of our web page dynamically without page refresh.
By using jQuery AJAX methods, we can request HTML, XML, or JSON from the server using both HTTP Get and HTTP Post requests.
Am assuming you are aware of C# Webservice, i.e., (ASMX file) Webservice.ASMX, WebMethods, and familiar with jQuery Ajax syntax.
And it's very useful if you want to save or insert data into the database without page postback or page refresh .i.e Insert data into the database using jQuery Ajax.
In this tutorial, we make a jQuery Ajax call and in response will get the JSON data, i.e., here we get a list of all cars and other detailed information from our database ( MS SQL server) via WebMethod (ASMX file).

Download the jQuery library and add Html Markup. Calling jQuery Ajax method. C#: Create Class and WebMethod, which returns JSON Object. First, we open Visual Studio IDE, create a new project, and then we added a new web page and named as myJsonTuts.aspx.

Add a reference to script files

On our web page, we add a button control and import jQuery library. You can download jQuery files, or you can use Google-hosted files. So now our HTML markup looks like as shown below. Now we write client-side code .i.e. on button click we make a jQuery Ajax call with returns JSON data, check this for dynamic button click event in jQuery. Here in our case, we fetch the list of cars along with other information from the database MS SQL server via C# WebMethod, which we create later on the server-side. Let's first check how our Client-side code looks as shown below. Here in the above code on our button click, we make an ajax call.

You may notice we have set dataType="JSON" that is because we want our ajax response in JSON format. Now we add a Webservice file (ASMX file) in our project, here we added a file and named it as myfunction.asmx.

In our Webservice (.asmx file) we also created a class .i.e Cars which has properties as carName, carRating, carYear.
Now we write a WebMethod as we want to get the list of all cars, here getListofCars is our WebMethod, which fires the select query to the database, pulls the record from the database, and adds it to our class object Car.
In response, we return this Car class object.
Note: Always use response.d to get the jquery ajax response in C#.
Thank you for reading, pls keep visiting this blog and share this in your network.
Also, I would love to hear your opinions down in the comments.
PS: If you found this content valuable and want to thank me?
👳 Buy Me a Coffee. ASP.NET Core is a modern web development framework by Microsoft.
You can build any type of projects – big or small, in this framework.

ASP.NET Core is based on Model View Controller (MVC) architecture where any HTTP based request is captured by a Controller which then passes the response to the View.

In the View you can make forms, which on submission, callsthe respective Action methods of the Controller. But in this process there will be a page reloading, however you can certainly avoid this page reloading by using jQuery AJAX method. In this tutorial you will learn how to use the jQuery AJAX method (.ajax())to call an Action method in ASP.NET Core. You can do the following things with the .ajax() method:. Call any Action method of the Controller. Pass values to Action parameters from the View. Get the response from the Action method and show it on the View. All these things happen with no page postback. Create a new ASP.NET Core application, and next, create a new ASP.NET Core Controller called HomeController inside the Controllers folder.

Create a new Action method called ‘Add’ inside theController that has the code shown below:. This Add Action method is fairly simple and takes 2 numbersto it’s parameter. It calculates the sum of these numbers and returns the sum at the end. Create a new ASP.NET Core View called Index.cshtml inside the Controllers ➤ Home folder and add the following jQuery code to it:.

Explanation: I defined 2 variables (val1 & val2) that contain 2 numbers which are 5 and 2.
Next I defined the .ajax() method of jQuery to call the ‘Add’ action method given in the Controller.
I gave the following values to it:.
type as POST – it means jQuery will make HTTP POST type of request to the ‘Add’ Action.
url as @Url.Action(“Add”) – it should be URL to which the Action method can be invoked.
I used the Url.Action() method to generate this URL based on the Routing system of my application.
Open the Startup.cs class of your application and see the routings given inside the Configure() method.

In my case it is:. That means the Action method’s URL based on this routingwill be – /Home/Add. data as {number1: val1, number2: val2} – here I give the values to the Action method’s parameters which are number1 and number2. The values should be specified in key-value manner like:.

Suppose you have 3 parameters instead of 2 like here. Thenthe data values would be specified as:. dataType as text – it specifies the type of response the ‘Add’ action will send. This Action method sends the response in ‘int’ so I used ‘text’.

Note that if the Action method sends the response in anybasic data types like int, float, string, double, bool etc , then specifydataType as ‘text’ for in .ajax() method.

success() – it is the callback function that executes if the .ajax() method executes successfully. error() – it is another callback function that executes if there is some failure when executing the .ajax() method.

Notice that in my success callback method I log the sum of the numbers on the console as shown below.
I have used jQuery AJAX extensively when calling ASP.NET Core Web APIs.

You can go through this tutorial at Call Web API from jQuery. It’s time to test the .ajax() method.

So run your application and go to the URL of the Index Action method. Since I added the .ajax() method on the Index action method of the Home controller, so it’s URL in my case is – http://localhost:51685/. Now open the console window and you will see 7 (which is thesum of 2 numbers 5 & 2) printed.

See the below image:. You have learned how to invoke action method that returns basic data type like Int by using .ajax() method of jQuery.

Now I will explain how to invoke an action method thatreturns JSON. I will add a new action method that will return JSON. So first create a new Model called Numbers.cs inside the model folder and add the below code to it:.

This class has 4 properties that will contain the Addition,Subtraction, Multiplication and Division of the 2 numbers. Next, create a new Action method called Calculate inside the Home Controller:. This Action method takes 2 numbers in its parameter and hasthe return type of Numbers object.

It first creates an object of ‘Number.cs’ class and stores the ‘Addition, Subtraction, Multiplication and Division’ of the 2 numbers in it’s 4 properties. JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. I have implemented JWT to make my APIs super secure. You can easily learn it at How to call a JWT secured APIs with jQuery AJAX.

In the end it simply returns back the ‘Number’ class object. Remember that in ASP.NET Core the complex objects areretuned as JSON by default. So that is the trick which I am using here to get JSON response from Action method in the jQuery AJAX. Now go to the Index Action method and comment out theprevious .ajax() method and add the new .ajax() method as shown below:. There are 2 small changes which are in the url of the Actionmethod:.

And dataType which is set as json:. Now re-run your application and check the console window.You will see the JSON response of the arithmetic operations:. Also see the below image which shown the printed response inthe console window:. It should also be noted that you can extract the individual values from this JSON like addition or subtraction values as:.

You can download the full codes of this tutorial from the below link:. I hope you liked this tutorial on jQuery AJAX usage in ASP.NET Core. My sincere advice for you is to learn .ajax() method and use it to make your website more user friendly and faster. Next tutorial : How to Install Bootstrap Package in ASP.NET Core Application in Visual Studio.

This article gives you step by step example for implementing Page Method and calling it through jQuery.ajax() call.

This example will read data from Customer table of Northwind database.
You can download the Northwind database here.
Depending on the selected Country value of DropDown, Customer details will be rendered if jQuery.ajax() call returns success.
jQuery library functions and methods have capabilities to load data from the server without a browser page refresh.
jQuery.Ajax() performs an asynchronous HTTP request.
This method can handle the response type of XML, JSON, script, or HTML.
If you are making a request to other domain datatype jsonp should be used.
You can perform asynchronously GET, POST, PUT or DELETE methods on the server using jQuery.Ajax().
Create new solution of ASP.NET.
Open visual studio click on File -> New -> Project -> ASP.NET Web Application name it as jQueryAjax and click Ok.
Open Default.aspx or create new page with name Customer.aspx.
In this step, we will add a DropDownList control to give users to select particular Country.
You can also try with jQuery AutoComplete TextBox.

We will also design a table object which will display Customer details on the selection of Country. The jQuery change event of DropDownList will be used to add rows to the table object. Add below html in BodyContent ContentPlaceHolder of Default.aspx. Open Site.css from Styles folder and add below styles to it. These styles are applied to table, table header and table row objects.

Add a new class as Customer.cs. This class will be used to hold customer details. jQuery.ajax() method will an get array of Customer object. Add below properties to Customer.cs . Open codebehind file of Default.aspx page.

Where we will add a PageMethod which takes Country as input parameter and return an array of Customer object. It makes a database call to SQL Server and gets customer details depending on the provided country. Add below code in Default.aspx.cs file. Notice that we have added [System.Web.Services.WebMethod] for GetCustomers method which allows access to methods by scripting method. In this step we will call PageMethod created in previous step. Create a new JavaScript file by open Solution Explorer -> right click on Scripts folder -> Select Add -> New Item -> Choose JScript -> Name it as Customer.js and click Ok .

Add function for ddlCountry DropDownList's change event. Whenever user change the selection of country, PageMethod will be called through jQuery.Ajax().

If the call is a successful it will read Customer details and add each customer as table row to tblCustomers.
$("#tblCustomers tbody tr").remove(); removes existing rows from table object.
Url is mentioned as "Default.aspx/GetCustomers" which indicates where your PageMethod exists.
PageMethod takes country as input parameter which is mentioned with data property of $.ajax.
success: function (data) { } will execute when PageMethod executes successfully.
It add row for each customer record.
failure: function (response) { } will execute if there is any error in execution of PageMethod and gives details of error.
Open Site.Master file and add a reference to the script file in head tag of Master page.
Your head tag will look like this.
Please login to post your comment!
super explanation with source code . thank you.
thanks senzeye, glad that it helped you .

This is prime example on how to write tutorials, thank you champ! Keep it up :) .

After that, the callback function will be invoked on the client, passing the string as the value for the data argument. As we have specified, the TextBox will be filled with the extracted value.

You can download a copy of this example at the bottom of the article in the file “SupportingDocuments”.

We’ve shown you, in the previous example, how to perform an AJAX request of a string to a web server and how to use it to refresh a web page. In reality, things are usually more complex. Only rarely do you have to update your page with only a simple text. Normally, a mix of data must be refreshed instead. To be able to do so, we need to understand how to pass complex data to the client and how to use it to refresh the page.

The most frequently used approach is to serialize our data using the JSON format and send the formatted string to the client for visualization. When data reach the client (with the callback invocation made by the server), JQuery is able to transform it in a JavaScript object that we can then use to refresh the page’s content.

To illustrate this, we’ll suppose that we want to visualize on the client not only a randomly selected sentence, but also the ID of the same. To do this, we add a second TextBox to the default.aspx page, with ID given by txtID. It will show the ID related to the sentence.

We need to modify the GetSentence method of the server in this way:

XDocument doc=XDocument.Load(Server.MapPath("/sentences.xml"));

This new method selects a sentence and then creates a JSON string that contains the id of the sentence in addition to the sentence’s text. The returned string will be something like this:


Where the and the are the id and the text of the selected sentence.

The OnLoad method of the page must be modified as follows:


We have modified the content type of the response from text/plain to application/json.

Finally, we change the JavaScript callback on the client in this way:


The JQuery .ajax() method automatically transforms the JSON string into a JavaScript object , on the basis of the content type of the response, and passes it to the success function. The created JavaScript object will have two properties: the .id properties with the id of the sentence and the .sentence property with the text of the same. This structure reflects the original JSON string structure. We use the two properties to update our page.

If you happen to use Microsoft AJAX and UpdatePanels, you probably know that Microsoft AJAX allows you to use a control named UpdateProgress to display some HTML code on the page immediately before the AJAX request and to hide it after it has completed.

This allows us to display, for example, an animated gif while the user is waiting for the completion of the request.

JQuery and its AJAX implementation allow you to perform the same thing, but by using some JavaScript code just before the AJAX request and just after the callback completion.

This can improve the user-experience thanks to the fact that you can now use a more dynamic JavaScript code rather than static HTML to generate visual effects on the client.

This can be done by using the following methods implemented on the JQuery library:

.ajaxStart(fn): Allows you to set a JavaScript callback-function to execute just before the AJAX request.

.ajaxComplete(fn): Specifies a JavaScript callback-function to execute just after the AJAX request completion.

This methods are attached to each page’s element when they are selected with the main JQuery function $.

Returning to our example, we surround our two TextBoxes with a div tag: giving to it the value ‘container‘ for its id property.

Although JQuery has a rich set of elements to perform animations of any type, we simply use the .hide() method to hide the TextBoxes just before the AJAX request, and the .show() method to show them again refreshed with the new values.

We can set the two argument functions of the two methods on the .ready() method of the JQuery library. Remember that this method is executed after the completion of the loading of the page, when it is ready to operate.

Our JavaScript code will be:


If you run the application, the two TextBoxes will be hidden after the button-click by reducing the div tag height to 0 with a speed given by the JQuery-defined value ‘normal‘. After the selection of the new sentence, the two TextBoxes will reappear on the page by resetting the height of the div tag to its original value with a speed identical to the previous.

You can download a copy of this example at the bottom of the article in the file “SupportingDocuments”.

In this article we’ve use JQuery to implement AJAX features on a web page. We have seen how easy it is to perform common AJAX tasks in JQuery (and in general JavaScript libraries that supports AJAX capabilities), because it is easier to modify those AJAX requests without being limited to perform only a partial rendering of the page. Partial rendering allow us only to update server controls contained on some UpdatePanel. The update occurs when we change some properties of those controls on the server side. With AJAX libraries we are free to select any kind of data source we want. We need only to serialize them, maybe using JSON, and send them to the client.

However, this doesn’t mean that ASP.NET UpdatePanels should not be used anymore. They are very easy to use and very quick to setup. With a simple drag and drop in Visual Studio, we have all the machinery to perform AJAX requests without having to write any other blocks of code. And this is the purpose of server controls: To make our life easier. When a server control can do it, allow it to do it, otherwise look elsewhere. And if you’re looking for more configurable AJAX work, then jQuery is a good library to consider.