Skip to content

Instantly share code, notes, and snippets.

@skttl
Last active October 21, 2016 07:23
Show Gist options
  • Save skttl/dbc8e2e792fb2389687bb5f470a2ecf1 to your computer and use it in GitHub Desktop.
Save skttl/dbc8e2e792fb2389687bb5f470a2ecf1 to your computer and use it in GitHub Desktop.
Extrension for getting values from a ViewDataDictionary Usage: @ViewData.GetValue<int>("someIntValue")
using System.Web.Mvc;
namespace MyWebsite.Core.Extensions
{
public static class ViewDataExtensions
{
/// <summary>
/// Gets value of dictionary key, returns defaultValue if key not found
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="viewData"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static T GetValue<T>(this ViewDataDictionary viewData, string key, T defaultValue = default(T))
{
return viewData.Keys.Contains(key) ? (T)viewData[key] : defaultValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment