MVC Form Helper

Moving away from ASP 3.0 Request.Form(" ...

As mentioned in my previous post, I wanted to find a way to auto-populate and entity object from the Request.Form collection. I also wanted (as an aside) to see if the grid still worked on MVC Preview 4 (it does). Here is the code:

public static T Request<T>(this Controller controller) where T : class, new()
    T o = new T();
    var request = controller.Request;
    foreach (var property in typeof(T).GetProperties())
        // Check if the object has the appropriate property
        var q = (request.Form.AllKeys
            .Where&lt;string>(s =&gt; s.ToLower() == property.Name.ToLower()))

        // if more than one... ignore
        if(q.Count == 1)
             string datum = request.Form[q[0]];
             if (property.PropertyType == typeof(string))
                 property.SetValue(o, datum, null);
                    Convert.ChangeType(datum, property.PropertyType),

    return o;

Notice that this is not an extension on the HtmlHelper since this will only be used inside the controller (hence a controller extension method). Here is how it is used:

Student s = this.Request<Student>();

Now for the explanation! The constraints on T (line 1, the where part) say that T must be a reference type and have a parameter-less constructor. I guess it doesn't have to have a parameter-less constructor but I thought it would be a pain to find out which request key matched up with which parameter in the constructor. I also thought that Entity classes should be POCO objects so they would naturally have an empty constructor. Some screenshots:





The Grid

I am continuing to work on the grid (this was a part of it). I just haven't gotten around to implementing the next thing all the way. The goal again was to have more control over how the grid should be rendered. I am borrowing some of the ideas from the MVCContrib grid but simplifying it a whole lot (for simple users like myself)

MVC Preview 4

I uninstalled preview 3 and then installed preview 4 and shortly after found that VS could not open my preview 3 stuff. Instead of rigging it, I just re-created the MVC part. The Controls assembly (the one with the grid) worked perfectly after correcting the references to the MVC dll's.

Your email address will not be published. Required fields are marked *