Home > DynaForms

DynaForms

DynaForms is a project mainly written in C#, it's free.

Generate HTML forms

With the help of the files DynaForms.cs & DynaFormTemplates.cs (just add them to your App_Code folder for your WebMatrix or MVC-projects) you can create and handle Html forms easily.

Basic add new form with built in templates:

var personForm = new DynaForm("person") .AddFormField("Name", required: true)
.AddFormField("Address") .AddFormField("Active", type: InputType.checkbox);

Basic add new form with custom templates:

Define the html template with parameters like this (idName will be replaced with id='{fieldName' name='{fieldName'}):

var customTemplate = "{labelText}: <input type='text' {idName} value='{value}'/>{errorMessage}
\n";

var f = new DynaForm("formname"); f.AddFormField("Name", template: customTemplate); f.AddFormField("Address", template: customTemplate);

Display form html:

@personForm.Html()

Based on the built in templates with the sample above it will create this form:

Handle post:

if (IsPost) { if (personForm.TryUpdateModel().IsValid) { // Form is valid. Get the model from the dynaform, by default it's an ExpandoObject: dynamic result = personForm.Model;

  // Insert result into the db
  db.Execute("INSERT INTO person (Name, Address, Active) VALUES (@0,@1,@2)", result.Name, result.Address, result.Active);
}
else
{
  // Form is not valid - show form again with validation error messages:
  @personForm.Html()
}

}

Use client side validation:

DynaForms create a jQuery Validate json-options string, which means you can add client side validation just by including these lines:

@Html.Raw(personForm.ClientSideScript())

Currently the client side rules are "required", "email", "maxlength", "minlength", "max" and "min". On server side there's also a Regex rule.

Change Html output for the controls:

Either:

  1. Add a custom template when you create your forms. Use the optional replace keywords, {idName}, {labelText}, {fieldName}, {value} and {errorMessage}

  2. Or change the default html templates for the "field controls" by editing the templates in DynaFormTemplates.cs: public const string TemplateInputText = @"

    {errorMessage}
    ";

Add plain Html to the forms

You can add plain Html with AddHtml(): var f = new DynaForm("formname") .AddHtml("

\n") .AddHtml(" Fieldset 1\n") .AddFormField("Name") .AddFormField("Address") .AddHtml("
\n");

More information:

There are tests and a sample to look at.

Previous:couchlegs