I am creating an ASP.NET application in which the administrator of the program will be able to define custom fields for forms that the users will fill out and submit.
The admin needs to define various types of fields like checkboxes, radio buttons, textboxes, and textareas for the user to fill out. The admin also can define whether these custom fields should be required.
I am in the planning stages now and am wondering about how I will store these custom field definitions in the database and how I will render them out and make them function.
The form data that is submitted by end users with these dynamically created form fields also has to be persisted in the database.
How can I tackle this problem?
Here is something I have whipped up real quick for proof of concept.
DynamicForms.zip
I built in VS 2008 SP1. There is a sql server db in the appdata folder, so sqlexpress will help if you want to run this.
I built this quickly, so it's pretty sloppy.
Without having done this or really anything like it, I would think your DB structure might include the type of control, its name, its value type, if its validated, how its validated, if its required. Then as you are reading through the records/dataset of controls desired, you would probably compare the control type in the recordset to the translated value and then add it to the webform.
For example:
if(drow["ControlType"].ToString().ToUpper() == "TEXTBOX")
{
Label lbl = new Label();
lbl.Text = drow["ControlLabel"].ToString();
TextBox txt = new TextBox();
//TO GET THE VALUE ON POSTBACK LATER
txt.ID = drow["ControlID"].ToString();
//PROBABLY NOT NECESSARY
Div myDiv = new Div();
myDiv.Controls.Add(lbl);
myDiv.Controls.Add(txt);
//ADD THE DIV ABOVE TO THE FORM/PANEL/DIV/ETC.
MyForm.Controls.Add(myDiv);
}
This in theory would put the label next to the textbox control. I have no idea if the Div would work, but you can run through this type of thing for CheckBox, TextBox, Label, etc.
Once the controls and labels are on the page, you'll want some form of action to cause the server to save the values to a DB. I'd recommend storing the table and column name with the list of objects. Then map the form field over to a DB column for the insert. (keep in mind this explanation is like at 200,000 feet)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With