I’ve seen a couple of methods on how to do this. My own method that I like, except from one part, is the following:
- Hijack submit-event of form
-
Collect the data and build a
jsonobjectvar objToSend = { Property : $('#propertyField').val(), Property2 : ... };This is the part I don’t like since it’s tedious to collect 25 values like this
-
Call
$.ajax({})and specify the url to point to an[HttpPost]enabled action somewhere - in the success: part of the ajax-query, collect the returned data (which I return as a string) and write it out where appropriate. I handle errors here as well, checking to see if the first word is “Error:” and then taking appropriate action.
I like this method apart from the collection stage. I am sure there is a better way of doing this but I’v thrown myself headlong into jquery coming from an ASP.NET WebForms-background so the whole “embrace the web” part is totally foreign to me.
You could use the
serialize()method to avoid passing all the fields one by one. It will send the entire form data to the server usingapplication/x-www-form-urlencodedcontent type as if it was a standard form submission:Another possibility is the jQuery form plugin:
Some people find it also useful to use the
Ajax.BeginFormhelpers to render the form:In ASP.NET MVC 3 you need to include the
jquery.unobtrusive-ajax.jsscript which unobtrusively AJAXifies the HTML 5data-*attributes emitted by the Ajax helper.