Ampliando la risposta di Hunter con un po 'Dorare ...
Il ViewData
Dictionary
è gloriosamente senza tipo.
Il modo più semplice per verificare la presenza di un valore (primo esempio di Hunter) è:
if (ViewData.ContainsKey("query"))
{
// your code
}
È possibile utilizzare un wrapper come [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;
}
}
che permette all'uomo di esprimere Il secondo esempio di Hunter come:
String.IsNullOrEmpty(ViewData.ItemCastOrDefault<String>("query"))
Ma in generale, mi piace avvolgere tali verifiche in nome intenzionale rivelatore metodi di estensione d, ad esempio:
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;
}
}
Che consente:
@if(ViewData.IncludesQuery())
{
...
var q = ViewData.Query();
}
Un esempio più elaborato di applicazione di questa tecnica:
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;
}
}
fonte
2016-02-01 13:15:12
Sembra funzionare in modo impeccabile usando la risposta originale :) – Cameron
Suggerirei di utilizzare un cast effettivo piuttosto che appoggiato a 'as' (e ho espanso su questa risposta con un'estensione che lo fa) (http: // stackoverflow. COM/a/35131514/11635)) –