Even easier form processing

Topics: blog
Sep 13, 2008 at 1:57 PM
Did you know that you can use foreach on a form? I've just created a new static class in the Fadd (.Net framework AddOns) project  which makes it possible to assign properties by using their name as a string. Since the HttpServer project uses Fadd, you can use this feature without having to download/use anything extra. The Property class will also parse or convert types when the value type is not the same as the property type. This makes it ideal for using with http forms where all values are string type.

Can it be simpler than this to assign an object from a http form or xml (using the XmlDecoder)?

// in UserController
string Save()
    User user = new User();
    foreach (HttpInputItem formItem in Request.Form["user"])
        Property.Set(user, formItem.Name, formItem.Value);

    // save the user

    return Render("Thank you " + user.FirstName);

The form looks like this (pseudocode):

<form method="post" action="/user/save/1">
<input name="user[FirstName]" value="Jonas" />
<input name="user[LastName]" value="Gauffin" />
<input name="user[Age]" value="32" />
<input name="user[Company]" value="Gauffin Telecom AB" />

The Property class will be slow the first time you run it on a new object, since it generates and compiles a new C# object which takes care of copying/conversion/parsing. This object is then saved in a dictionary and reused every time the same type of object is requested.