20

I use the following in my View to check if a query exists like domain.com/?query=moo

if (!string.IsNullOrEmpty(Request.QueryString["query"])) { my code }

But now need to change it so that it checks if the ViewData query exists instead of the query string, but not quite sure how to rewrite it. My ViewData looks like this: ViewData["query"]

Can anyone help? Thanks

Cameron
  • 27,963
  • 100
  • 281
  • 483

4 Answers4

25
if (ViewData["query"] != null) 
{
    // your code
}

if you absolutely have to get a string value you can do:

string query = (ViewData["query"] ?? string.Empty) as string;
if (!string.IsNullOrEmpty(query)) 
{
    // your code
}
hunter
  • 62,308
  • 19
  • 113
  • 113
  • I'd suggest using an actual cast rather than leaning on `as` (and have [expanded on this answer with an extension that does this](http://stackoverflow.com/a/35131514/11635)) – Ruben Bartelink Feb 01 '16 at 13:16
7

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;
    }
}
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
3
  <% if(ViewData["query"]!=null)
    { 
    if((!string.IsNullOrEmpty(ViewData["query"].ToString())) 
      {
        //code 
       }
    }
   %>
Vishal
  • 12,133
  • 17
  • 82
  • 128
  • If `ViewData["query"] == null` this will explode. Lots of folks trying to `ToString()` nulls... lots of folks exploding – hunter Jan 13 '11 at 16:05
  • yea..updated it..still checking for empty strings just in case ! – Vishal Jan 13 '11 at 16:08
1

If you ever had to do this in one line - for example in Razor

ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "What I'm looking for"

I'm trying to use ViewData to figure out whether or not the current Action is the one that needs to be Active in my navigation bar

<li class="@(ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "Configuration" ? "active" : null)">
Matty Bear
  • 517
  • 1
  • 4
  • 16