Expanding on Hunter's answer with some goldplating...
The ViewData
Dictionary
is gloriously untyped.
The simplest way to check for presence of a value (Hunter's first example) is:
if (ViewData.ContainsKey("query"))
{
// your code
}
You can use a wrapper like [1]:
public static class ViewDataExtensions
{
public static T ItemCastOrDefault<T>(this ViewDataDictionary that, string key)
{
var value = that[key];
if (value == null)
return default(T);
else
return (T)value;
}
}
which enables one to express Hunter's second example as:
String.IsNullOrEmpty(ViewData.ItemCastOrDefault<String>("query"))
But in general, I like to wrap such checks in intention revealing named extension methods, e.g.:
public static class ViewDataQueryExtensions
{
const string Key = "query";
public static bool IncludesQuery(this ViewDataDictionary that)
{
return that.ContainsKey("query");
}
public static string Query(this ViewDataDictionary that)
{
return that.ItemCastOrDefault<string>(Key) ?? string.Empty;
}
}
Which enables:
@if(ViewData.IncludesQuery())
{
...
var q = ViewData.Query();
}
A more elaborate example of applying this technique:
public static class ViewDataDevExpressExtensions
{
const string Key = "IncludeDexExpressScriptMountainOnPage";
public static bool IndicatesDevExpressScriptsShouldBeIncludedOnThisPage(this ViewDataDictionary that)
{
return that.ItemCastOrDefault<bool>(Key);
}
public static void VerifyActionIncludedDevExpressScripts(this ViewDataDictionary that)
{
if (!that.IndicatesDevExpressScriptsShouldBeIncludedOnThisPage())
throw new InvalidOperationException("Actions relying on this View need to trigger scripts being rendered earlier via this.ActionRequiresDevExpressScripts()");
}
public static void ActionRequiresDevExpressScripts(this Controller that)
{
that.ViewData[Key] = true;
}
}
as
(and have expanded on this answer with an extension that does this) – Abrasive