views:

18

answers:

1

This extremely cool article written in the winter of 2007 shows me this code:

public static class TempDataExtensions
{
  public static void PopulateFrom(this TempDataDictionary tempData, object o)
  {
    foreach (PropertyValue property in o.GetProperties())
    {
      tempData[property.Name] = property.Value;
    }
  }

  public static void PopulateFrom(this TempDataDictionary tempData
    , NameValueCollection nameValueCollection)
  {
    foreach (string key in nameValueCollection.Keys)
      tempData[key] = nameValueCollection[key];
  }

  public static void PopulateFrom(this TempDataDictionary tempData
    , IDictionary<string, object> dictionary)
  {
    foreach (string key in dictionary.Keys)
      tempData[key] = dictionary[key];
  }

  public static string SafeGet(this TempDataDictionary tempData, string key)
  { 
    object value;
    if (!tempData.TryGetValue(key, out value))
      return string.Empty;
    return value.ToString();
  }
}

I'm not seeing any code like this in the MVCContrib source or in MVC2 source. This makes me think that I can still use this pattern now without fear of the equivalent functionality already living in the current MVC2 release (might be in MVC3 Preview 1?).

I did not see any update edits to the article. Does this MVC code from 2007 stand the test of time? Is it still ready for now?

+1  A: 

Yes, this will work and this functionality is not replaced.

One caveat. In MVC 1 Temp data stayed around for one request only. With MVC 2 tempdata now stays around until you access it or manually clear it. This could complicate things if your redirect fails or never reads the tempdata.

The new dynamic keyword will also provide similar functionality maybe the new new C# 4.0 dynamic type may clean things up a little.

jfar