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:

   1:          public static T Request<T>(this Controller controller) where T : class, new()
   2:          {
   3:              T o = new T();
   4:              var request = controller.Request;
   5:              foreach (var property in typeof(T).GetProperties())
   6:              {
   7:                  // Check if the object has the appropriate property
   8:                  var q = (request.Form.AllKeys
   9:                      .Where<string>(s => s.ToLower() == property.Name.ToLower()))
  10:                      .ToList<string>();
  11:   
  12:                  // if more than one... ignore
  13:                  if(q.Count == 1)
  14:                  {
  15:                      string datum = request.Form[q[0]];
  16:                      if (property.PropertyType == typeof(string))
  17:                          property.SetValue(o, datum, null);
  18:                      else
  19:                          property.SetValue(o,
  20:                              Convert.ChangeType(datum, property.PropertyType),
  21:                              null);
  22:                  }
  23:              }
  24:   
  25:              return o;
  26:          }

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:

   1:  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:

Before:

image

After:

image

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Comments

Add comment


 

  Country flag


  • Comment
  • Preview
Loading