A neat way to submit forms via Ajax using JQuery

I am currently working on a web application using Microsoft’s ASP.NET MVC framework. Most of the actions / page interactions are done via Ajax calls. When submitting a form, typically my JavaScript looked something like this:

// Get the values 
var company = { Name : $('input:name=companyName').val(),
Address1 : $('input:name=companyAddress1').val(),
Address2 : $('input:name=companyAddress2').val(),
City : $('input:name=companyCity').val(),
State : $('input:name=companyState').val(),
ZipCode : $('input:name=companyZipCode').val() }

// Send request
$.post('/CompanyMaintenance/Add', company, function(data) {
$('#ResultDiv').html(data);
}, "html");

However, I came across the following useful article:

http://stackoverflow.com/questions/267707/how-to-pass-complex-type-using-json-to-asp-net-mvc-controller

Using this approach, I don’t need to manually pull out all the values from the input elements, I can automatically serialize all the elements in my form. Also, if I’m smart about naming the elements in my form, the object I get will be automatically recognized by my Controller at the .NET side. For example, if I name my elements like this:

<form id="CompanyAddForm">
<input type="Text" name="company.Name"/>
<input type="Text" name="company.Address1"/>
etc.

and then my JavaScript can be like this:

var company = $('#CompanyAddForm').serializeArray();

// Send request
$.post('/CompanyMaintenance/Add', company, function(data) {
$('#ResultDiv').html(data);
}, "html");

My controller action (at the .NET side) will then look like this:

public ActionResult(Company company)
{
    companyService.Add(company)
    ... etc.
}

Additionally I can also use the same kind of code to do this from ASP.NET WebForms using the Ajax Pro library for Ajax. The main difference in the page is that there is only one Form, so I’ll have to make clever use of JQuery here, but essentially I could do something like this:

<div id="CompanyAddDiv">
<input type="Text" name="company.Name"/>
<input type="Text" name="company.Address1"/>
etc.

// Seralize all input elements
// within the 'CompanyAddDiv' div
var company = $('#CompanyAddDiv input').serializeArray();

// Send request
var result = CompanyPage.Add(company);

$('#ResultDiv').html(result.value);
Advertisement

1 comment so far

  1. [...] | Tags: Ajax, ASP.NET, ASP.NET MVC, javascript, JQuery, Microsoft MVC, MVC, MVC2 | In a previous post I talked about a neat way to submit forms via Ajax using jQuery. In another, more recent post I [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.