Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
namespace <your_namespace>
{
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System;
public static class ViewDataExtension
{
/// <summary>
/// Get value at <see cref="ViewDataDictionary"/> by key.
/// </summary>
/// <typeparam name="TModel">Type of model with values.</typeparam>
/// <typeparam name="T">Result type of object.</typeparam>
/// <param name="viewData">Dictionary of values.</param>
/// <param name="key">The key on which the value is searched.</param>
/// <param name="defaultValue">Default value if cannot found at dictionary.</param>
/// <returns>Returns value of key from dictionary or default value.</returns>
public static T GetValue<TModel, T>(this ViewDataDictionary<TModel> viewData, string key, T defaultValue = default(T))
{
if (string.IsNullOrEmpty(key) || !viewData.IsNull())
{
object tryGetValue;
if (viewData.TryGetValue(key, out tryGetValue))
return (T)tryGetValue;
}
return defaultValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment