I have some ideas how to tackle this, but it must be a relatively common thing to do and I wondered if there is a ‘standard’ way to tackle it.
Basically I have a form on an HTML page which uses jQuery AJAX to post to an ASP.NET page, which then takes the form fields and puts them into a database.
The form itself contains some standard fields, such as article title, article content and date. However, the form also allows for numerous author details to be added, comprising author name, author email address, author age. So on the form, the user fills in the form title and content fields and can add one or more authors, the fields for which are built dynamically using jQuery.clone().
So there is an unknown number of authors, and as a result the .NET control which accepts the form post doesn’t know what fields it is due to receive.
The standard form details are added to one table, called ‘Article’. The authors are each individually added to a different table, called ‘Author’.
So the question is, what is the best way to handle this type of thing?
Thanks for any advice here.
EDIT:
To add my initial ideas to this… Firstly, I could name each of the author form fields with an incremental number, like this:
<fieldset>
Author 1 name: <input name="name-1" /><br />
Author 1 email: <input name="email-1" /><br />
Author 1 age: <input name="age-1" />
</fieldset>
<fieldset>
Author 2 name: <input name="name-2" /><br />
Author 2 email: <input name="email-2" /><br />
Author 2 age: <input name="age-2" />
</fieldset>
And also have a hidden field called ‘number-of-authors’ which is incremented/decremented when new author fieldsets are added/removed by the jQuery script. Then in the .NET code which receives the form post, I could loop through each form field from 0 to x (where x is the value of ‘number-of-authors’. The difficulty here is I’d have to re-index each of the form fields when a fieldset is removed, in case the user deletes the first set, for example.
My second thought is that I could use jQuery serialisation to serialise the form field values into a single string, then process that string back into an object in the .NET code. Although I don’t really know how to do this, I’m sure it would be possible.
What would people’s advice be in this situation?
Since you can’t read a dynamic table on postback, I normally read all my rows into objects and pass them back to the server in a WebMethod or WCF Service. I use this same technique for both Ajax forms and Traditional postback forms.
Here is a quick summary of what I do.
HTML
JavaScript
Code Behind