The purpose of this article is to showcase how to submit a form to an ASP.NET Page via AJAX using JQuery. Why would we use AJAX to submit a form when developing an ASP.NET application? That is an application design question. However, if it has been decided that AJAX will be used, then JQuery can help you make your codebase smaller and also make the code cross-browser compliant. JQuery does a lot more and for that please feel free to refer to the JQuery site (http://jquery.com/
The sample application revolves around accepting some contact details, posting them to an ASP.NET form and then displaying the data received by the server. The sample code can be downloaded from the following zip.
2. Next, create a default asp.net website and rename default.aspx to “SaveContact.aspx”
3. You may also have to add a web.config file from add new items as in VS 2005, it may not add by default for a website
Open “SaveContact.aspx” in the designer and remove all the HTML tags (see screenshot
5. Add default.htm and include the jquery script file and create the form shown in the code snippet (see screenshot)
Now add the jquery function to submit the form and receive the results as shown in the code snippet (see screenshot
7. $() represents the JQuery object
9. $("#submit_btn").click() searches for an element with ID as submit_btn and adds a function to the click event
10. $.post expects 3 arguments
a. The name of the page to which the form will be posted
b. The arguments which need to be posted
c. The function to be called on receiving the response
11. The return false ensure that the there is no page refresh after the call is completed
12. Response contains the entire HTML output of SaveContact.aspx
13. Here we have taken the response set it to the inner HTML of a DIV using $("#DivResult").html(response).show()
14. # is the keyword used to refer to a the ID of an element.
15. .html() is a function in JQuery to update the inner HTML. You can also use the same function to get the inner HTML.
16. Show() causes the div to be displayed immediately, even if it is hidden. This is particularly useful if you keep your div hidden by default.
On the code behind of SaveContact.aspx, add the code in the screenshot
18. While it is quite possible to save the received result into a database writing simple ADO.NET code, the purpose of this article was to keep focus on the core aspect, i.e., showcase how we can bring the data and submit a response
19. Given below is the screen shot of a sample input and output generated from the code. Please feel free to try any other data too. The application has been tried on IE7, Firefox 2+ and Chrome 1+. Barring a few discrepancies in the UI, the functionality is the same in all 3 browsers.