HTML forms seem to be general enough to warrant a better abstraction than manually creating the HTML, or even using simple HTML helpers. Ideally the semantics of the form should be enough to generate all the HTML content.
I have been prototyping some ideas in this area. Here is some code that demonstrates a simple (but incomplete) login form.
class LoginData
{ public string Username { get; set; } public string Password { get; set; } public bool Persist { get; set; }}
class LoginForm : Form<LoginData>
{ public LoginForm()
{ FieldContainer = new DivFieldContainer();
Add(d => d.Username);
Add(d => d.Password).AsPassword();
Add(d => d.Persist).WithLabel("Stay logged in on this computer"); }
}
class Program
{ static void Main(string[] args)
{ var data = new LoginData() { Username = "test" }; var form = new LoginForm();
var html = form.Create(data);
Console.WriteLine(html.ToString());
}
}
This generates the following HTML.
<form method="POST" action="http://localhost/">
<div>
<label for="Username">Username</label>
<input id="Username" type="text" name="Username" value="test" />
</div>
<div>
<label for="Password">Password</label>
<input id="Password" type="password" name="Password" />
</div>
<div>
<input id="Persist" type="checkbox" name="Persist" />
<label for="Persist">Stay logged in on this computer</label>
</div>
</form>
There is a clear separation of the data from the form meta-data. This lets me do interesting things like applying conventions, for example, the generation of label text from property names. I want to use mostly global conventions for a form, and then override a few specific fields where needed.
I think validation can also fit nicely into this approach. Validation logic can be put on the data model. The form model can then specify how errors are added to the HTML.
Has anyone else seen anything like this before? I don’t want the reinvent the wheel. Or at least I can steal some good ideas ;)