0

这篇写于 2007 年冬天的非常酷的文章向我展示了这段代码:

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();
  }
}

我在 MVCContrib 源代码或 MVC2 源代码中没有看到任何这样的代码。这让我觉得我现在仍然可以使用这种模式,而不必担心当前 MVC2 版本中已经存在的等效功能(可能在 MVC3 Preview 1 中?)。

我没有看到对文章的任何更新编辑。这个 2007 年的 MVC 代码是否经得起时间的考验?现在还准备好了吗?

4

1 回答 1

1

是的,这将起作用,并且此功能不会被替换。

一个警告。在 MVC 1 中,临时数据仅针对一个请求保留。使用 MVC 2,临时数据现在会一直存在,直到您访问它或手动清除它。如果您的重定向失败或从不读取临时数据,这可能会使事情复杂化。

新的动态关键字也将提供类似的功能,也许新的 C# 4.0 动态类型可能会清理一些东西。

于 2010-07-31T03:35:30.060 回答